fix(core,board,ecommerce,page,gdpr,basic): 깊은 OFFSET 목록 조회 개선 및 raw/테이블명 전수 정리

목록이 뒤쪽 페이지로 갈수록 느려지는 원인은 건너뛰는 행의 넓은 컬럼까지 읽는 것이었다.
지연 조인(inner 는 키 컬럼만, outer 는 이번 페이지 행만 전체 컬럼)과 정렬 컬럼 해석을
코어 공통 트레이트로 두고 코어 8 + 확장 6 저장소에 적용했다.

감사 지적 처리:
- 그룹 쿼리의 총 건수 오산 — count 는 groupBy 를 벗기지 않아 첫 그룹의 행 수를
 총 건수로 돌려준다. getCountForPagination 으로 교정.
- audit 전수 스캔이 버퍼 한계로 한 번도 동작하지 않던 결함과, 확장 경로를 놓치던
 정규식 5건을 함께 고쳤다. 그동안 번들 확장의 위반이 보이지 않았다.

raw 20건을 빌더 표현으로 치환하고 하드코딩 테이블명 16건을 모델 유래로 바꿨다.
이 과정에서 마이페이지 「내가 댓글 단 글」 검색이 조인 별칭 충돌로 SQL 오류를 내던
결함이 해소됐다. 재발 차단용 룰 2종을 신설하고, 컬럼 프루닝 룰을 error 로 승격했다
(전역 위반 0건 — warning 으로 두면 "0 error" 판정을 통과하며 무음으로 재누적된다).

정렬 허용 목록은 FormRequest 게이트를 덮어야 한다. 좁으면 검증을 통과한 정렬이 422 도
로그도 없이 기본값으로 되돌아간다(스케줄 실행 이력의 종료시각·소요시간 정렬이 그랬다).
호출처를 스캔해 매핑 완전성까지 검사하는 계약 테스트로 전수 강제한다.

해외 배송지 결함도 함께 고쳤다 — 조회는 city/state/postal_code 로 내려주고 폼은
intl_* 로 제출하는 비대칭 때문에, 수정 시 입력칸이 비어 보이고 저장하면 기존 값이
유실됐다. 쿠폰 수정의 유효기간 미검증과 1인당 사용 제한 부분 수정 차단도 함께 수정.
This commit is contained in:
HeuJung committed 2026-08-02 14:36:37 +09:00
1 parent 95ffdf9eed
commit be9befe023
81 files changed
+5799 -457

No files matched your search

@@ -0,0 +1,235 @@
/**
* E2E: 지연 조인 전환 후 목록 페이지네이션 종단 확인
*
* 목록 조회가 "이번 페이지의 ID 를 먼저 구하고, 그 ID 에 대해서만 목록 컬럼과 관계를 읽는"
* 2단계로 바뀌었다. 단위 테스트는 쿼리 구조와 ID 시퀀스를 잠그지만, 실제 화면에서 드러나는
* 증상(마지막 페이지에서 "다음" 이 계속 눌리거나, 페이지 이동 후 목록이 비어 보이거나,
* 콘솔에 렌더 에러가 남는 것)은 브라우저 레벨에서만 잡힌다.
*
* 계획서의 브라우저 확인 항목을 화면별로 잠근다:
* (1) 목록이 렌더된다 (관계/컬럼 프루닝으로 화면이 비지 않는다)
* (2) 마지막 페이지에서 "다음" 이 비활성이다 (총 건수 계산 정합)
* (3) 콘솔/페이지 에러가 없다
*
* 데이터 의존 스킵: 목록이 한 페이지 분량이면 페이지네이션 컨트롤이 없으므로 (2)를 건너뛴다.
* 스킵 사유는 실행 로그에 남는다 — 조용한 통과가 아니다.
*
* @scenario case=deep_offset_list_browser
*
* @effects pages_do_not_overlap_or_drop_rows, simple_mode_reports_last_page_without_next
*/
import type { Page } from '@playwright/test';
import { test, expect, authenticatePage, issueToken } from '../../fixtures/auth';
/** 점검 대상 화면 — 계획서가 지목한 4개 목록 */
const LIST_SCREENS = [
{ name: '활동 로그', path: '/admin/activity-logs', permissions: ['core.activities.read'] },
{ name: '알림 발송 이력', path: '/admin/notification-logs', permissions: ['core.notification-logs.read'] },
{ name: '관리자 주문 목록', path: '/admin/ecommerce/orders', permissions: ['sirsoft-ecommerce.orders.read'] },
{
name: '게시판 게시글 목록',
path: '/admin/board/notice',
permissions: ['sirsoft-board.notice.admin.posts.read', 'sirsoft-board.notice.admin.manage'],
},
] as const;
/**
* 관리자 화면 진입 공통 대기 (기존 admin spec 과 동일 패턴).
*
* `networkidle` 은 폴링/실시간 연결이 있는 화면에서 영영 idle 이 되지 않아 쓰지 않는다.
*
* @param page 대상 페이지
* @param path 이동할 경로
*/
async function gotoAdmin(page: Page, path: string): Promise<void> {
await page.goto(path);
await page.waitForLoadState('domcontentloaded', { timeout: 30_000 });
await page.waitForFunction(
() => !window.location.pathname.includes('/admin/login') || document.readyState === 'complete',
{ timeout: 15_000 },
);
}
/**
* 페이지에서 수집한 콘솔/페이지 에러를 담을 배열을 부착합니다.
*
* @param page 대상 페이지
* @returns 수집된 에러 메시지 배열 (테스트 진행에 따라 채워진다)
*/
function collectPageErrors(page: Page): string[] {
const errors: string[] = [];
page.on('console', (message) => {
if (message.type() === 'error') {
errors.push(message.text());
}
});
page.on('pageerror', (error) => {
errors.push(error.message);
});
return errors;
}
/**
* 목록 데이터가 도착할 때까지 기다립니다.
*
* 진입 직후에는 목록이 비어 있어 페이지네이션이 아직 렌더되지 않는다. 데이터 로드를
* 기다리지 않고 컨트롤 개수를 세면 "컨트롤 없음" 으로 잘못 판정해 조용히 스킵된다.
*
* @param page 대상 페이지
* @returns 행이 하나라도 렌더되면 true
*/
async function waitForListRows(page: Page): Promise<boolean> {
return page
.locator('tbody tr, [data-testid$="-row"]')
.first()
.waitFor({ state: 'attached', timeout: 20_000 })
.then(() => true)
.catch(() => false);
}
/**
* 페이지네이션의 "다음" 컨트롤을 찾습니다.
*
* `aria-label` 은 앱 로케일에 따라 한국어("다음 페이지")로도, 언어팩이 아직 붙지 않은
* 시점에는 기본 영문("Next page")으로도 렌더된다. 한쪽만 보면 컨트롤이 있는데도
* "없음" 으로 판정해 조용히 스킵되므로 양쪽을 모두 매칭한다.
*
* @param page 대상 페이지
* @returns 다음 페이지 컨트롤 locator
*/
function nextPageControl(page: Page) {
return page
.locator(
[
'[aria-label="다음 페이지"]',
'[aria-label="Next page"]',
'[data-testid="pagination-next"]',
'button:has-text("다음")',
].join(', '),
)
.first();
}
/**
* 페이지네이션의 "마지막 페이지" 컨트롤을 찾습니다.
*
* @param page 대상 페이지
* @returns 마지막 페이지 컨트롤 locator
*/
function lastPageControl(page: Page) {
return page.locator('[aria-label="마지막 페이지"], [aria-label="Last page"]').first();
}
/**
* "다음" 컨트롤이 비활성인지 판정합니다.
*
* @param page 대상 페이지
* @returns 비활성이면 true
*/
async function isNextDisabled(page: Page): Promise<boolean> {
const next = nextPageControl(page);
if ((await next.count()) === 0) {
return true;
}
if (await next.isDisabled().catch(() => false)) {
return true;
}
return (await next.getAttribute('aria-disabled')) === 'true';
}
test.describe('목록 페이지네이션 (지연 조인)', () => {
for (const screen of LIST_SCREENS) {
// @scenario case=deep_offset_list_browser
// @effects pages_do_not_overlap_or_drop_rows
test(`${screen.name} — 목록이 렌더되고 페이지 에러가 없다`, async ({ page }) => {
const errors = collectPageErrors(page);
await authenticatePage(page, issueToken(...screen.permissions));
await gotoAdmin(page, screen.path);
if (/\/admin\/login/.test(page.url())) {
test.skip(true, `${screen.name} 접근 불가 — 확장 미설치 또는 권한 미부여`);
return;
}
// 목록 컨테이너가 떠야 한다 — 렌더 자체가 깨지면 여기서 잡힌다.
await expect(
page.locator('table, [role="table"], [data-testid$="-list"]').first(),
).toBeAttached({ timeout: 20_000 });
await waitForListRows(page);
expect(errors, `페이지 에러: ${errors.join(' | ')}`).toHaveLength(0);
});
// @scenario case=deep_offset_list_browser
// @effects simple_mode_reports_last_page_without_next
test(`${screen.name} — 마지막 페이지에서 "다음" 이 비활성이다`, async ({ page }) => {
await authenticatePage(page, issueToken(...screen.permissions));
await gotoAdmin(page, screen.path);
if (/\/admin\/login/.test(page.url())) {
test.skip(true, `${screen.name} 접근 불가 — 확장 미설치 또는 권한 미부여`);
return;
}
if (! (await waitForListRows(page))) {
test.skip(true, `${screen.name} 목록 행 없음 — 데이터 미존재`);
return;
}
const next = nextPageControl(page);
// 목록 행과 페이지네이션은 렌더 시점이 다르다. 행이 떴다고 바로 세면 아직 없는
// 컨트롤을 "없음" 으로 오판해 조용히 스킵된다 — 컨트롤이 붙을 때까지 기다린다.
const hasControl = await next
.waitFor({ state: 'attached', timeout: 15_000 })
.then(() => true)
.catch(() => false);
if (! hasControl) {
test.skip(true, `${screen.name} 페이지네이션 컨트롤 없음 — 데이터가 한 페이지 분량`);
return;
}
// 마지막 페이지로 한 번에 이동한다. 컨트롤이 없는 템플릿이면 "다음" 을 반복 클릭한다.
// 이미 마지막 페이지면(한 페이지 분량) 이동 없이 곧바로 판정한다 — 비활성 버튼을
// 클릭하려 들면 Playwright 가 enabled 를 기다리다 타임아웃한다.
const last = lastPageControl(page);
const alreadyLast = await isNextDisabled(page);
if (alreadyLast) {
// 이동 불필요
} else if ((await last.count()) > 0 && (await last.isEnabled().catch(() => false))) {
await last.click();
} else {
for (let hop = 0; hop < 10; hop += 1) {
if (await isNextDisabled(page)) {
break;
}
await next.click();
await page.waitForTimeout(1_000);
}
}
// 고정 대기 대신 상태가 바뀔 때까지 폴링한다 — 병렬 실행에서 서버 응답이 늦어도
// 결과 판정이 흔들리지 않는다.
await expect
.poll(() => isNextDisabled(page), {
message: '마지막 페이지에서 "다음" 이 계속 활성이면 총 건수 계산이 어긋난 것이다',
timeout: 20_000,
})
.toBe(true);
});
}
});
@@ -0,0 +1,161 @@
<?php
namespace Tests\Unit\Repositories\Concerns;
use PHPUnit\Framework\Attributes\DataProvider;
use Tests\TestCase;
/**
* 지연 조인 호출 계약 전수 검사
*
* 개별 저장소마다 페이지 경계 테스트를 손으로 나열하면 새 호출처가 늘어날 때 조용히 빠진다.
* 여기서는 **호출처를 스캔해서 도출**한 뒤 계약 위반을 기계적으로 판정한다.
*
* 검사하는 계약 (PaginatesWithDeferredJoin docblock 의 "호출 계약"):
* - `columns:` 를 명시할 것 — 생략하면 outer 가 무엇을 읽는지 호출처에서 드러나지 않는다
* - `sort:` 를 명시하고 비우지 말 것 — 정렬이 비면 키 컬럼만 남아 화면 정렬이 사라진다
*
* `columns: ['*']` 자체는 위반이 아니다. 지연 조인의 목적인 **OFFSET 구간의 넓은 컬럼 읽기**는
* inner 가 키 컬럼만 읽는 것으로 이미 제거되고, outer 가 읽는 행 수는 페이지 크기로 고정된다.
* 넓은 컬럼을 가진 테이블에서 컬럼을 좁히는 것은 그 위에 얹는 추가 최적화다.
*
* @scenario case=deferred_join_call_site_contract
*
* @effects call_sites_declare_columns, call_sites_declare_sort
*/
class DeferredJoinCallSiteContractTest extends TestCase
{
/** 스캔 대상 루트 (저장소 상대) */
private const SCAN_ROOTS = ['app', 'modules/_bundled', 'plugins/_bundled'];
/**
* 지연 조인 호출처를 스캔해 돌려줍니다.
*
* @return array<string, array{0: string, 1: int, 2: string}> [파일, 줄번호, 인자 텍스트]
*/
public static function callSiteProvider(): array
{
// tests/Unit/Repositories/Concerns → 저장소 루트
$root = dirname(__DIR__, 4);
$cases = [];
foreach (self::SCAN_ROOTS as $scanRoot) {
$base = $root.DIRECTORY_SEPARATOR.str_replace('/', DIRECTORY_SEPARATOR, $scanRoot);
if (! is_dir($base)) {
continue;
}
$iterator = new \RecursiveIteratorIterator(
new \RecursiveDirectoryIterator($base, \FilesystemIterator::SKIP_DOTS)
);
foreach ($iterator as $file) {
if (! $file->isFile() || $file->getExtension() !== 'php') {
continue;
}
$path = str_replace('\\', '/', $file->getPathname());
// 트레이트 본체와 테스트 코드는 호출처가 아니다
if (str_contains($path, '/tests/') || str_contains($path, '/Concerns/PaginatesWithDeferredJoin.php')) {
continue;
}
$content = file_get_contents($path);
if (! str_contains($content, 'paginateWithDeferredJoin(')) {
continue;
}
foreach (self::extractCallSites($content) as [$line, $args]) {
$relative = substr($path, strlen(str_replace('\\', '/', $root)) + 1);
$cases["{$relative}:{$line}"] = [$relative, $line, $args];
}
}
}
return $cases;
}
/**
* 파일 내용에서 호출처의 인자 텍스트를 추출합니다.
*
* @param string $content 파일 내용
* @return array<int, array{0: int, 1: string}> [줄번호, 인자 텍스트]
*/
private static function extractCallSites(string $content): array
{
$sites = [];
$offset = 0;
while (($pos = strpos($content, 'paginateWithDeferredJoin(', $offset)) !== false) {
$open = $pos + strlen('paginateWithDeferredJoin(') - 1;
$depth = 0;
$end = null;
for ($i = $open; $i < strlen($content); $i++) {
$ch = $content[$i];
if ($ch === '(' || $ch === '[') {
$depth++;
} elseif ($ch === ')' || $ch === ']') {
$depth--;
if ($depth === 0) {
$end = $i;
break;
}
}
}
if ($end === null) {
break;
}
$line = substr_count(substr($content, 0, $pos), "\n") + 1;
$sites[] = [$line, substr($content, $open + 1, $end - $open - 1)];
$offset = $end;
}
return $sites;
}
#[DataProvider('callSiteProvider')]
public function test_call_site_declares_columns(string $file, int $line, string $args): void
{
$this->assertMatchesRegularExpression(
'/\bcolumns\s*:/',
$args,
"{$file}:{$line} — columns: 를 명시해야 한다 (미지정 시 outer 가 읽는 범위가 호출처에서 보이지 않는다)"
);
$this->assertDoesNotMatchRegularExpression(
'/\bcolumns\s*:\s*\[\s*\]/',
$args,
"{$file}:{$line} — 빈 컬럼 목록은 어떤 컬럼도 선택하지 않는다"
);
}
#[DataProvider('callSiteProvider')]
public function test_call_site_declares_sort_spec(string $file, int $line, string $args): void
{
$this->assertMatchesRegularExpression(
'/\bsort\s*:/',
$args,
"{$file}:{$line} — sort: 를 명시해야 한다 (미지정 시 키 컬럼 정렬만 남는다)"
);
$this->assertDoesNotMatchRegularExpression(
'/\bsort\s*:\s*\[\s*\]/',
$args,
"{$file}:{$line} — 빈 정렬 스펙은 화면 정렬을 잃는다"
);
}
public function test_scan_finds_call_sites(): void
{
// 스캔이 0건이면 위 두 테스트가 조용히 통과해 계약 검사가 무력화된다
$this->assertNotEmpty(self::callSiteProvider(), '지연 조인 호출처를 하나도 찾지 못했다 — 스캔 경로를 확인할 것');
}
}
@@ -0,0 +1,690 @@
<?php
namespace Tests\Unit\Repositories\Concerns;
use App\Repositories\Concerns\PaginatesWithDeferredJoin;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Pagination\Paginator;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Tests\TestCase;
/**
* 지연 조인 페이지네이션 Trait 단위 테스트
*
* 성능 수치가 아니라 **쿼리 구조**를 단언한다. 절대 시간 임계값은 CI 머신 성능에 좌우되지만
* "넓은 컬럼이 OFFSET 스캔에 포함되지 않는다"는 구조는 기계가 판정할 수 있고, 누군가 나중에
* inner 에 `with()` 를 다시 붙이거나 목록 컬럼을 되돌리면 즉시 실패한다.
*/
class PaginatesWithDeferredJoinTest extends TestCase
{
use RefreshDatabase;
/** 수집된 실행 쿼리 SQL 목록 */
private array $queries = [];
protected function setUp(): void
{
parent::setUp();
Schema::create('deferred_join_samples', function ($table) {
$table->id();
$table->unsignedBigInteger('group_id')->default(1);
$table->string('title', 100);
$table->unsignedInteger('view_count')->default(0);
$table->longText('body')->nullable();
$table->timestamps();
$table->softDeletes();
});
Schema::create('deferred_join_sample_comments', function ($table) {
$table->id();
$table->unsignedBigInteger('sample_id');
$table->string('content', 100);
$table->timestamps();
});
}
protected function tearDown(): void
{
Schema::dropIfExists('deferred_join_sample_comments');
Schema::dropIfExists('deferred_join_samples');
parent::tearDown();
}
/**
* 샘플 행을 생성합니다.
*
* @param int $count 생성 건수
* @param int $viewCount 조회수 (동률 tie-break 검증용 고정값)
*/
private function seedSamples(int $count, int $viewCount = 0): void
{
$rows = [];
for ($i = 1; $i <= $count; $i++) {
$rows[] = [
'group_id' => 1,
'title' => "제목 {$i}",
'view_count' => $viewCount,
'body' => str_repeat('본문 ', 200),
'created_at' => now(),
'updated_at' => now(),
];
}
DB::table('deferred_join_samples')->insert($rows);
}
/** 쿼리 로그 수집을 시작합니다. */
private function startCapture(): void
{
$this->queries = [];
DB::listen(function ($query) {
$this->queries[] = $query->sql;
});
}
/**
* 수집된 쿼리 중 조건에 맞는 것만 돌려줍니다.
*
* @param string $needle 포함 문자열
* @return array<int, string> 일치 쿼리 목록
*/
private function queriesContaining(string $needle): array
{
return array_values(array_filter($this->queries, fn (string $sql) => str_contains($sql, $needle)));
}
/** 테스트용 리포지토리를 생성합니다. */
private function repository(): object
{
return new class
{
use PaginatesWithDeferredJoin;
/**
* 지연 조인 페이지네이션을 그대로 노출합니다. (Trait 메서드는 protected)
*
* @param Builder $query 대상 쿼리
* @param array $args 나머지 인자
*/
public function paginate(Builder $query, array $columns, array $sort, int $perPage, ...$args)
{
return $this->paginateWithDeferredJoin($query, $columns, $sort, $perPage, ...$args);
}
};
}
/**
* @scale n=200000 asserts=id_only_inner_query
*/
public function test_inner_query_selects_only_key_column_without_wide_columns(): void
{
$this->seedSamples(30);
$this->startCapture();
$this->repository()->paginate(
DeferredJoinSample::query(),
['id', 'title'],
[['column' => 'id', 'direction' => 'asc']],
10,
2,
);
$offsetQueries = $this->queriesContaining('offset');
$this->assertCount(1, $offsetQueries, 'OFFSET 스캔은 정확히 한 번(inner)만 일어나야 한다');
// 테이블 프리픽스는 환경 설정값이므로 패턴으로 판정한다
$this->assertMatchesRegularExpression('/^select `[^`]*deferred_join_samples`\.`id` from/', $offsetQueries[0]);
$this->assertStringNotContainsString('body', $offsetQueries[0], 'inner 는 넓은 컬럼을 읽지 않아야 한다');
$this->assertStringNotContainsString('title', $offsetQueries[0]);
}
/**
* @scale n=200000 asserts=no_wide_column_in_offset_scan
*/
public function test_outer_query_filters_by_id_set_without_offset(): void
{
$this->seedSamples(30);
$this->startCapture();
$this->repository()->paginate(
DeferredJoinSample::query(),
['id', 'title'],
[['column' => 'id', 'direction' => 'asc']],
10,
2,
);
$outer = $this->queriesContaining('`id` in (');
$this->assertNotEmpty($outer, 'outer 는 ID 집합으로 조회해야 한다');
$this->assertStringNotContainsString('offset', $outer[0], 'outer 에는 OFFSET 이 없어야 한다');
}
public function test_relations_are_not_eager_loaded_for_inner_query(): void
{
$this->seedSamples(5);
DB::table('deferred_join_sample_comments')->insert([
['sample_id' => 1, 'content' => '댓글', 'created_at' => now(), 'updated_at' => now()],
]);
$this->startCapture();
$result = $this->repository()->paginate(
DeferredJoinSample::query()->with('comments'),
['id', 'title'],
[['column' => 'id', 'direction' => 'asc']],
10,
1,
['comments'],
);
$commentQueries = $this->queriesContaining('deferred_join_sample_comments');
$this->assertCount(1, $commentQueries, '관계 쿼리는 outer 에서 한 번만 실행되어야 한다');
$this->assertTrue($result->getCollection()->first()->relationLoaded('comments'));
}
public function test_count_query_is_skipped_when_total_is_injected(): void
{
$this->seedSamples(30);
$this->startCapture();
$result = $this->repository()->paginate(
DeferredJoinSample::query(),
['id', 'title'],
[['column' => 'id', 'direction' => 'asc']],
10,
1,
[],
[],
'id',
30,
);
$this->assertEmpty($this->queriesContaining('count(*)'), '주입된 total 이 있으면 COUNT 를 실행하지 않아야 한다');
$this->assertInstanceOf(LengthAwarePaginator::class, $result);
$this->assertSame(30, $result->total());
}
public function test_simple_mode_skips_count_and_detects_next_page(): void
{
$this->seedSamples(25);
$this->startCapture();
$result = $this->repository()->paginate(
DeferredJoinSample::query(),
['id', 'title'],
[['column' => 'id', 'direction' => 'asc']],
10,
1,
[],
[],
'id',
null,
true,
);
$this->assertEmpty($this->queriesContaining('count(*)'));
$this->assertInstanceOf(Paginator::class, $result);
$this->assertCount(10, $result->items(), 'perPage + 1 건을 읽어도 페이지 항목은 perPage 건이어야 한다');
$this->assertTrue($result->hasMorePages());
}
public function test_simple_mode_reports_last_page_correctly(): void
{
$this->seedSamples(15);
$result = $this->repository()->paginate(
DeferredJoinSample::query(),
['id', 'title'],
[['column' => 'id', 'direction' => 'asc']],
10,
2,
[],
[],
'id',
null,
true,
);
$this->assertCount(5, $result->items());
$this->assertFalse($result->hasMorePages(), '마지막 페이지에서 다음 페이지가 있다고 보고하면 안 된다');
}
public function test_tie_breaking_key_is_appended_to_sort_spec(): void
{
// 모든 행의 view_count 가 동일 — 키 컬럼 tie-break 가 없으면 페이지 경계가 흔들린다
$this->seedSamples(20, viewCount: 7);
$page1 = $this->repository()->paginate(
DeferredJoinSample::query(),
['id', 'view_count'],
[['column' => 'view_count', 'direction' => 'desc']],
10,
1,
);
$page2 = $this->repository()->paginate(
DeferredJoinSample::query(),
['id', 'view_count'],
[['column' => 'view_count', 'direction' => 'desc']],
10,
2,
);
$firstIds = $page1->getCollection()->pluck('id')->all();
$secondIds = $page2->getCollection()->pluck('id')->all();
$this->assertSame([20, 19, 18, 17, 16, 15, 14, 13, 12, 11], $firstIds);
$this->assertSame([10, 9, 8, 7, 6, 5, 4, 3, 2, 1], $secondIds);
$this->assertEmpty(array_intersect($firstIds, $secondIds), '페이지 간 중복 행이 없어야 한다');
}
public function test_outer_result_order_matches_inner_order(): void
{
$this->seedSamples(12);
$result = $this->repository()->paginate(
DeferredJoinSample::query(),
['id', 'title'],
[['column' => 'title', 'direction' => 'asc']],
5,
1,
);
$ids = $result->getCollection()->pluck('id')->all();
$sorted = $result->getCollection()->sortBy('title')->pluck('id')->all();
$this->assertSame(array_values($sorted), $ids, 'outer 결과 순서가 정렬 스펙과 일치해야 한다');
}
public function test_soft_deleted_rows_stay_excluded(): void
{
$this->seedSamples(10);
DeferredJoinSample::query()->whereIn('id', [3, 7])->delete();
$result = $this->repository()->paginate(
DeferredJoinSample::query(),
['id', 'title'],
[['column' => 'id', 'direction' => 'asc']],
20,
1,
);
$ids = $result->getCollection()->pluck('id')->all();
$this->assertNotContains(3, $ids);
$this->assertNotContains(7, $ids);
$this->assertSame(8, $result->total());
}
public function test_with_trashed_scope_is_preserved(): void
{
$this->seedSamples(10);
DeferredJoinSample::query()->whereIn('id', [3, 7])->delete();
$result = $this->repository()->paginate(
DeferredJoinSample::query()->withTrashed(),
['id', 'title'],
[['column' => 'id', 'direction' => 'asc']],
20,
1,
);
$this->assertSame(10, $result->total());
$this->assertContains(3, $result->getCollection()->pluck('id')->all());
}
public function test_filters_applied_to_query_are_preserved(): void
{
$this->seedSamples(10);
DB::table('deferred_join_samples')->whereIn('id', [2, 4, 6])->update(['group_id' => 9]);
$result = $this->repository()->paginate(
DeferredJoinSample::query()->where('group_id', 9),
['id', 'group_id'],
[['column' => 'id', 'direction' => 'asc']],
10,
1,
);
$this->assertSame([2, 4, 6], $result->getCollection()->pluck('id')->all());
$this->assertSame(3, $result->total());
}
public function test_preserve_id_order_restores_inner_sequence(): void
{
$this->seedSamples(6);
$result = $this->repository()->paginate(
DeferredJoinSample::query(),
['id', 'title'],
[['column' => 'id', 'direction' => 'desc']],
3,
1,
[],
[],
'id',
null,
false,
true,
);
$this->assertSame([6, 5, 4], $result->getCollection()->pluck('id')->all());
}
public function test_with_count_is_applied_on_outer_only(): void
{
$this->seedSamples(3);
DB::table('deferred_join_sample_comments')->insert([
['sample_id' => 1, 'content' => 'a', 'created_at' => now(), 'updated_at' => now()],
['sample_id' => 1, 'content' => 'b', 'created_at' => now(), 'updated_at' => now()],
]);
$result = $this->repository()->paginate(
DeferredJoinSample::query(),
['id', 'title'],
[['column' => 'id', 'direction' => 'asc']],
10,
1,
[],
['comments'],
);
$this->assertSame(2, (int) $result->getCollection()->firstWhere('id', 1)->comments_count);
}
public function test_grouped_query_total_counts_groups_not_first_group_rows(): void
{
// 조인으로 행이 불어난 뒤 groupBy 로 접히는 형태 — 조인 행 7건, 그룹 5건
$this->seedSamples(5);
DB::table('deferred_join_sample_comments')->insert([
['sample_id' => 1, 'content' => 'a', 'created_at' => now(), 'updated_at' => now()],
['sample_id' => 1, 'content' => 'b', 'created_at' => now(), 'updated_at' => now()],
['sample_id' => 1, 'content' => 'c', 'created_at' => now(), 'updated_at' => now()],
['sample_id' => 2, 'content' => 'd', 'created_at' => now(), 'updated_at' => now()],
['sample_id' => 3, 'content' => 'e', 'created_at' => now(), 'updated_at' => now()],
['sample_id' => 4, 'content' => 'f', 'created_at' => now(), 'updated_at' => now()],
['sample_id' => 5, 'content' => 'g', 'created_at' => now(), 'updated_at' => now()],
]);
$result = $this->repository()->paginate(
DeferredJoinSample::query()
->join('deferred_join_sample_comments as c', 'c.sample_id', '=', 'deferred_join_samples.id')
->groupBy('deferred_join_samples.id'),
['deferred_join_samples.id'],
[['column' => 'deferred_join_samples.id', 'direction' => 'asc']],
10,
1,
);
// 집계 쿼리를 서브쿼리로 감싸지 않으면 첫 그룹의 행 수(3)가 총 건수로 잡힌다
$this->assertSame(5, $result->total(), '그룹 쿼리의 총 건수는 그룹 수여야 한다');
$this->assertCount(5, $result->items());
$this->assertSame(1, $result->lastPage());
}
public function test_grouped_query_paginates_across_pages_with_correct_total(): void
{
$this->seedSamples(12);
$rows = [];
for ($sampleId = 1; $sampleId <= 12; $sampleId++) {
// 1번 샘플만 댓글 5건 — 첫 그룹 행 수와 그룹 수를 다르게 만든다
$repeat = $sampleId === 1 ? 5 : 1;
for ($i = 0; $i < $repeat; $i++) {
$rows[] = ['sample_id' => $sampleId, 'content' => "c{$sampleId}-{$i}", 'created_at' => now(), 'updated_at' => now()];
}
}
DB::table('deferred_join_sample_comments')->insert($rows);
$grouped = fn () => DeferredJoinSample::query()
->join('deferred_join_sample_comments as c', 'c.sample_id', '=', 'deferred_join_samples.id')
->groupBy('deferred_join_samples.id');
$page2 = $this->repository()->paginate(
$grouped(),
['deferred_join_samples.id'],
[['column' => 'deferred_join_samples.id', 'direction' => 'asc']],
5,
2,
);
$this->assertSame(12, $page2->total());
$this->assertSame(3, $page2->lastPage());
$this->assertSame([6, 7, 8, 9, 10], $page2->getCollection()->pluck('id')->all());
}
public function test_returned_paginator_supports_query_string_appending(): void
{
// 필터 조건을 페이지 링크에 보존하는 책임은 호출자의 appends()/withQueryString() 에 있다.
// 지연 조인 전환 후에도 그 계약이 유지되는지 확인한다 (Laravel paginate() 도 동일).
$this->seedSamples(30);
$result = $this->repository()->paginate(
DeferredJoinSample::query(),
['id', 'title'],
[['column' => 'id', 'direction' => 'asc']],
10,
1,
);
$url = $result->appends(['search' => '검색어', 'sort' => 'latest'])->nextPageUrl();
$this->assertStringContainsString('search=', (string) $url);
$this->assertStringContainsString('sort=latest', (string) $url);
$this->assertStringContainsString('page=2', (string) $url);
}
public function test_custom_page_name_is_reflected_in_paginator_links(): void
{
$this->seedSamples(30);
$result = $this->repository()->paginate(
DeferredJoinSample::query(),
['id', 'title'],
[['column' => 'id', 'direction' => 'asc']],
10,
1,
[],
[],
'id',
null,
false,
false,
'p',
);
$this->assertStringContainsString('p=2', (string) $result->nextPageUrl());
}
/**
* 깊은 OFFSET 의 비용 증가가 유계인지 확인합니다.
*
* 절대 시간 임계값(`assertLessThan(50, $ms)`)은 CI 머신 성능에 좌우되므로 쓰지 않는다.
* 대신 **같은 머신 안에서의 비율**만 단언한다 — 뒤쪽 페이지 소요 시간이 첫 페이지의 몇 배인가.
* 지연 조인 이전에는 이 비율이 20배를 넘었고(OFFSET 이 커질수록 넓은 컬럼을 그만큼 더 읽는다),
* 이후에는 넓은 컬럼을 읽는 행 수가 페이지 크기로 고정되므로 배수가 상수에 가깝게 붙는다.
* 상한 5배는 실측(21.6배 → ~2배)에 여유를 둔 값이다.
*
* @scale n=200000 asserts=deep_offset_bounded_growth
*/
public function test_deep_offset_cost_growth_is_bounded(): void
{
$rows = 20000;
$perPage = 20;
// 넓은 컬럼(longText)이 있어야 OFFSET 구간의 읽기 비용 차이가 드러난다
$body = str_repeat('본문 ', 250);
$now = now();
for ($chunk = 0; $chunk < $rows / 1000; $chunk++) {
$batch = [];
for ($i = 1; $i <= 1000; $i++) {
$batch[] = [
'group_id' => 1,
'title' => '제목 '.($chunk * 1000 + $i),
'view_count' => 0,
'body' => $body,
'created_at' => $now,
'updated_at' => $now,
];
}
DB::table('deferred_join_samples')->insert($batch);
}
$measure = function (int $page) use ($perPage): float {
$run = fn () => $this->repository()->paginate(
DeferredJoinSample::query(),
['id', 'title', 'body'],
[['column' => 'id', 'direction' => 'asc']],
$perPage,
$page,
);
$run(); // 버퍼 풀 워밍 — 첫 회는 버린다
$samples = [];
for ($i = 0; $i < 5; $i++) {
$start = microtime(true);
$run();
$samples[] = (microtime(true) - $start) * 1000;
}
sort($samples);
return $samples[2]; // 중앙값
};
$firstPage = $measure(1);
$lastPage = $measure((int) ($rows / $perPage));
$this->assertGreaterThan(0.0, $firstPage, '측정값이 0 이면 비율 판정이 무의미하다');
$ratio = $lastPage / $firstPage;
$this->assertLessThanOrEqual(
5.0,
$ratio,
sprintf(
'마지막 페이지가 첫 페이지의 %.1f배 — 깊은 OFFSET 비용이 유계가 아니다 (첫 %.2fms / 마지막 %.2fms)',
$ratio,
$firstPage,
$lastPage
)
);
}
/**
* 지연 조인 결과가 기존 `paginate()` 와 **같은 ID 시퀀스**인지 확인합니다.
*
* 정적 골든 fixture 를 파일로 떠 두면 기대값을 사람이 다시 만들어야 해서, 정렬 규칙이
* 바뀔 때 fixture 를 함께 고쳐 회귀를 덮어버리기 쉽다. 여기서는 **교체 전 경로 자체**
* (`Builder::paginate`)를 오라클로 두고 매 실행마다 기대값을 다시 얻는다. 순서까지
* 비교하므로 tie-break 회귀도 잡힌다.
*/
public function test_id_sequence_matches_plain_paginate_oracle(): void
{
// 조회수가 겹치도록 만들어 tie-break 가 개입하게 한다
for ($i = 1; $i <= 47; $i++) {
DB::table('deferred_join_samples')->insert([
'group_id' => $i % 3,
'title' => sprintf('제목 %03d', $i),
'view_count' => $i % 5,
'body' => str_repeat('본문 ', 50),
'created_at' => now(),
'updated_at' => now(),
]);
}
$perPage = 10;
$sort = [
['column' => 'view_count', 'direction' => 'desc'],
['column' => 'id', 'direction' => 'asc'],
];
foreach ([1, 2, 3, 5] as $page) {
$oracle = DeferredJoinSample::query()
->where('group_id', '!=', 2)
->orderBy('view_count', 'desc')
->orderBy('id', 'asc')
->paginate($perPage, ['id'], 'page', $page);
$actual = $this->repository()->paginate(
DeferredJoinSample::query()->where('group_id', '!=', 2),
['id', 'title'],
$sort,
$perPage,
$page,
);
$this->assertSame(
$oracle->getCollection()->pluck('id')->all(),
$actual->getCollection()->pluck('id')->all(),
"{$page}페이지의 ID 시퀀스가 기존 paginate() 결과와 달라졌다"
);
$this->assertSame($oracle->total(), $actual->total(), "{$page}페이지의 총 건수가 달라졌다");
$this->assertSame($oracle->lastPage(), $actual->lastPage());
}
}
public function test_empty_result_does_not_run_outer_query(): void
{
$this->startCapture();
$result = $this->repository()->paginate(
DeferredJoinSample::query(),
['id', 'title'],
[['column' => 'id', 'direction' => 'asc']],
10,
1,
);
$this->assertTrue($result->getCollection()->isEmpty());
$this->assertEmpty($this->queriesContaining('`id` in ('), '빈 결과에서는 outer 쿼리를 실행하지 않아야 한다');
}
}
/**
* 지연 조인 테스트용 샘플 모델
*/
class DeferredJoinSample extends Model
{
use SoftDeletes;
protected $table = 'deferred_join_samples';
protected $guarded = [];
/**
* 샘플 댓글 관계
*
* @return HasMany 댓글 관계
*/
public function comments()
{
return $this->hasMany(DeferredJoinSampleComment::class, 'sample_id');
}
}
/**
* 지연 조인 테스트용 샘플 댓글 모델
*/
class DeferredJoinSampleComment extends Model
{
protected $table = 'deferred_join_sample_comments';
protected $guarded = [];
}
@@ -0,0 +1,143 @@
<?php
namespace Tests\Unit\Repositories\Concerns;
use App\Repositories\Concerns\ResolvesSortSpec;
use PHPUnit\Framework\TestCase;
/**
* 정렬 스펙 해석 Trait 단위 테스트
*
* 요청 유래 값이 화이트리스트 밖으로 새지 않는지, 그리고 부적절한 값이 와도 기본값으로
* 안전하게 폴백하는지를 고정한다.
*/
class ResolvesSortSpecTest extends TestCase
{
/** 테스트용 리포지토리를 생성합니다. */
private function repository(): object
{
return new class
{
use ResolvesSortSpec;
/**
* 정렬 스펙 해석을 그대로 노출합니다. (Trait 메서드는 protected)
*
* @param array $args resolveSortSpec 인자
* @return array 정렬 스펙
*/
public function resolve(...$args): array
{
return $this->resolveSortSpec(...$args);
}
};
}
public function test_allowed_column_and_direction_pass_through(): void
{
$spec = $this->repository()->resolve(
['sort_by' => 'created_at', 'sort_order' => 'asc'],
['id', 'created_at', 'status'],
'id',
);
$this->assertSame([['column' => 'created_at', 'direction' => 'asc']], $spec);
}
public function test_unknown_column_falls_back_to_default(): void
{
$spec = $this->repository()->resolve(
['sort_by' => 'admin_memo', 'sort_order' => 'desc'],
['id', 'created_at'],
'id',
);
$this->assertSame('id', $spec[0]['column']);
}
public function test_invalid_direction_falls_back_to_default(): void
{
$spec = $this->repository()->resolve(
['sort_by' => 'created_at', 'sort_order' => 'sideways'],
['created_at'],
'created_at',
'asc',
);
$this->assertSame('asc', $spec[0]['direction']);
}
public function test_column_alias_is_applied_before_whitelist_check(): void
{
$spec = $this->repository()->resolve(
['sort_by' => 'author', 'sort_order' => 'desc'],
['id', 'author_name'],
'id',
'desc',
['author' => 'author_name'],
);
$this->assertSame('author_name', $spec[0]['column']);
}
public function test_custom_filter_keys_are_honored(): void
{
$spec = $this->repository()->resolve(
['order_by' => 'view_count', 'order_direction' => 'asc'],
['id', 'view_count'],
'id',
'desc',
[],
'order_by',
'order_direction',
);
$this->assertSame([['column' => 'view_count', 'direction' => 'asc']], $spec);
}
public function test_backed_enum_values_are_normalized(): void
{
$spec = $this->repository()->resolve(
['sort_by' => SampleSortColumn::CreatedAt, 'sort_order' => SampleSortDirection::Asc],
['id', 'created_at'],
'id',
);
$this->assertSame([['column' => 'created_at', 'direction' => 'asc']], $spec);
}
public function test_missing_and_blank_values_fall_back(): void
{
$spec = $this->repository()->resolve(
['sort_by' => ' '],
['id', 'created_at'],
'created_at',
'desc',
);
$this->assertSame([['column' => 'created_at', 'direction' => 'desc']], $spec);
}
public function test_array_value_is_rejected(): void
{
$spec = $this->repository()->resolve(
['sort_by' => ['created_at'], 'sort_order' => ['asc']],
['id', 'created_at'],
'id',
);
$this->assertSame([['column' => 'id', 'direction' => 'desc']], $spec);
}
}
/** 테스트용 정렬 컬럼 Enum */
enum SampleSortColumn: string
{
case CreatedAt = 'created_at';
}
/** 테스트용 정렬 방향 Enum */
enum SampleSortDirection: string
{
case Asc = 'asc';
}
@@ -0,0 +1,248 @@
<?php
namespace Tests\Unit\Repositories\Concerns;
use PHPUnit\Framework\Attributes\DataProvider;
use Tests\TestCase;
/**
* 정렬 허용 컬럼 ↔ 검증 게이트 정합 전수 검사
*
* 허용 값의 SSoT 는 요청을 실제로 거절하는 FormRequest 이고, Repository 의 정렬 상수는
* 그 아래에 깔리는 안전망이다. 상수가 게이트의 **부분집합**이면 검증을 통과한 정렬이 조용히
* 기본값으로 되돌아간다 — 422 도 로그도 남지 않아 "정렬 버튼이 안 먹는다" 로만 관측된다.
*
* 실제 사례: ScheduleHistoryRepository 가 게이트의 `ended_at`/`duration` 대신 존재하지 않는
* 컬럼 `finished_at` 을 허용 목록에 담아, 종료시각·소요시간 정렬이 무음으로 죽어 있었다.
*
* 손으로 나열한 매핑은 새 호출처가 생기면 조용히 빠지므로, **매핑의 완전성 자체를 스캔으로
* 검증**한다 (test_every_call_site_is_mapped). 새 resolveSortSpec 호출처를 추가하고 매핑을
* 등록하지 않으면 이 테스트가 실패한다.
*
* @scenario case=sortable_columns_gate_contract
*
* @effects repo_whitelist_covers_gate, every_call_site_mapped
*/
class SortableColumnsGateContractTest extends TestCase
{
/** 스캔 대상 루트 (저장소 상대) */
private const SCAN_ROOTS = ['app/Repositories', 'modules/_bundled', 'plugins/_bundled'];
/**
* Repository 파일 → 대응 FormRequest 파일 매핑
*
* 값이 null 이면 "요청 경로가 없는 내부 전용 호출" 을 뜻하며 게이트 대조를 건너뛴다.
*
* @var array<string, string|null>
*/
private const GATE_MAP = [
'app/Repositories/ActivityLogRepository.php' => 'app/Http/Requests/ActivityLog/ActivityLogIndexRequest.php',
'app/Repositories/IdentityMessageDefinitionRepository.php' => 'app/Http/Requests/Admin/Identity/AdminIdentityMessageDefinitionIndexRequest.php',
'app/Repositories/MenuRepository.php' => 'app/Http/Requests/Menu/MenuListRequest.php',
'app/Repositories/NotificationDefinitionRepository.php' => 'app/Http/Requests/NotificationDefinition/NotificationDefinitionIndexRequest.php',
'app/Repositories/NotificationLogRepository.php' => 'app/Http/Requests/NotificationLog/NotificationLogIndexRequest.php',
'app/Repositories/ScheduleHistoryRepository.php' => 'app/Http/Requests/Schedule/ScheduleHistoryListRequest.php',
'app/Repositories/ScheduleRepository.php' => 'app/Http/Requests/Schedule/ScheduleListRequest.php',
'app/Repositories/UserRepository.php' => 'app/Http/Requests/User/UserListRequest.php',
'modules/_bundled/sirsoft-ecommerce/src/Repositories/CouponRepository.php' => 'modules/_bundled/sirsoft-ecommerce/src/Http/Requests/Admin/CouponListRequest.php',
'modules/_bundled/sirsoft-ecommerce/src/Repositories/ExtraFeeTemplateRepository.php' => 'modules/_bundled/sirsoft-ecommerce/src/Http/Requests/Admin/ExtraFeeTemplateListRequest.php',
'modules/_bundled/sirsoft-ecommerce/src/Repositories/OrderRepository.php' => 'modules/_bundled/sirsoft-ecommerce/src/Http/Requests/Admin/OrderListRequest.php',
'modules/_bundled/sirsoft-ecommerce/src/Repositories/ProductRepository.php' => 'modules/_bundled/sirsoft-ecommerce/src/Http/Requests/Admin/ProductListRequest.php',
'modules/_bundled/sirsoft-ecommerce/src/Repositories/ShippingPolicyRepository.php' => 'modules/_bundled/sirsoft-ecommerce/src/Http/Requests/Admin/ShippingPolicyListRequest.php',
'modules/_bundled/sirsoft-page/src/Repositories/PageRepository.php' => 'modules/_bundled/sirsoft-page/src/Http/Requests/PageListRequest.php',
];
/**
* 저장소 루트 절대경로를 돌려줍니다.
*
* @return string 저장소 루트 경로
*/
private static function repositoryRoot(): string
{
// tests/Unit/Repositories/Concerns → 저장소 루트
return dirname(__DIR__, 4);
}
/**
* resolveSortSpec 을 호출하는 파일 목록을 스캔합니다.
*
* @return array<int, string> 저장소 상대 경로 목록
*/
private static function scanCallSites(): array
{
$root = self::repositoryRoot();
$found = [];
foreach (self::SCAN_ROOTS as $scanRoot) {
$base = $root.DIRECTORY_SEPARATOR.str_replace('/', DIRECTORY_SEPARATOR, $scanRoot);
if (! is_dir($base)) {
continue;
}
$iterator = new \RecursiveIteratorIterator(
new \RecursiveDirectoryIterator($base, \FilesystemIterator::SKIP_DOTS)
);
foreach ($iterator as $file) {
if (! $file->isFile() || $file->getExtension() !== 'php') {
continue;
}
$path = str_replace('\\', '/', $file->getPathname());
$relative = ltrim(str_replace(str_replace('\\', '/', $root), '', $path), '/');
// 트레이트 본체와 테스트 코드는 호출처가 아니다
if (str_contains($relative, '/tests/') || str_contains($relative, 'Concerns/ResolvesSortSpec.php')) {
continue;
}
if (str_contains((string) file_get_contents($path), '$this->resolveSortSpec(')) {
$found[] = $relative;
}
}
}
sort($found);
return $found;
}
/**
* 게이트 대조 대상 케이스를 제공합니다.
*
* @return array<string, array{0: string, 1: string}> [저장소 파일, 요청 파일]
*/
public static function gatePairProvider(): array
{
$cases = [];
foreach (self::GATE_MAP as $repository => $request) {
if ($request === null) {
continue;
}
$cases[$repository] = [$repository, $request];
}
return $cases;
}
/**
* 파일에서 정렬 허용 컬럼 집합을 추출합니다. (상수 참조 해석 포함)
*
* @param string $content 파일 내용
* @return array<int, string> 허용 컬럼 목록
*/
private function extractRepositoryColumns(string $content): array
{
$columns = [];
// resolveSortSpec 의 두 번째 인자 — self::CONST 또는 인라인 배열
preg_match_all('/resolveSortSpec\(\s*\$\w+\s*,\s*(self::(\w+)|\[[^\]]*\])/s', $content, $matches, PREG_SET_ORDER);
foreach ($matches as $match) {
$literal = $match[1];
if (str_starts_with($literal, 'self::')) {
$constName = $match[2];
if (! preg_match('/const\s+'.preg_quote($constName, '/').'\s*=\s*\[(.*?)\];/s', $content, $constMatch)) {
continue;
}
$literal = $constMatch[1];
}
preg_match_all("/'([a-zA-Z0-9_]+)'/", $literal, $columnMatches);
$columns = array_merge($columns, $columnMatches[1]);
}
return array_values(array_unique($columns));
}
/**
* FormRequest 에서 sort_by 허용 값을 추출합니다.
*
* @param string $content 파일 내용
* @return array<int, string> 허용 값 목록
*/
private function extractGateColumns(string $content): array
{
// 'sort_by' => ... 한 줄(또는 Rule::in 블록) 안의 in: / Rule::in([...]) 를 읽는다
if (! preg_match("/'sort_by'\s*=>\s*(.*?)(?:\],|\],\s*$|\n\s*'[a-z_]+'\s*=>)/s", $content, $match)) {
return [];
}
$rule = $match[1];
$columns = [];
if (preg_match('/Rule::in\(\[(.*?)\]\)/s', $rule, $ruleInMatch)) {
preg_match_all("/'([a-zA-Z0-9_]+)'/", $ruleInMatch[1], $columnMatches);
$columns = $columnMatches[1];
} elseif (preg_match('/in:([a-zA-Z0-9_,]+)/', $rule, $inMatch)) {
$columns = explode(',', $inMatch[1]);
}
return array_values(array_filter(array_unique($columns)));
}
/**
* 모든 resolveSortSpec 호출처가 매핑에 등록되어 있는지 검사합니다.
*/
public function test_every_call_site_is_mapped(): void
{
$callSites = self::scanCallSites();
$this->assertNotEmpty($callSites, 'resolveSortSpec 호출처를 하나도 찾지 못했습니다 — 스캔 경로를 확인하세요.');
$unmapped = array_diff($callSites, array_keys(self::GATE_MAP));
$this->assertSame(
[],
array_values($unmapped),
"GATE_MAP 에 등록되지 않은 resolveSortSpec 호출처가 있습니다:\n ".implode("\n ", $unmapped)
."\n대응 FormRequest 를 매핑에 추가하세요 (요청 경로가 없으면 null)."
);
$stale = array_diff(array_keys(self::GATE_MAP), $callSites);
$this->assertSame(
[],
array_values($stale),
"GATE_MAP 에 남아 있으나 더 이상 resolveSortSpec 을 호출하지 않는 항목:\n ".implode("\n ", $stale)
);
}
/**
* Repository 정렬 허용 목록이 FormRequest 게이트를 모두 덮는지 검사합니다.
*
* @param string $repositoryPath 저장소 상대 경로 (Repository)
* @param string $requestPath 저장소 상대 경로 (FormRequest)
*/
#[DataProvider('gatePairProvider')]
public function test_repository_whitelist_covers_gate(string $repositoryPath, string $requestPath): void
{
$root = self::repositoryRoot();
$repositoryFile = $root.DIRECTORY_SEPARATOR.str_replace('/', DIRECTORY_SEPARATOR, $repositoryPath);
$requestFile = $root.DIRECTORY_SEPARATOR.str_replace('/', DIRECTORY_SEPARATOR, $requestPath);
$this->assertFileExists($repositoryFile, "매핑된 Repository 파일이 없습니다: {$repositoryPath}");
$this->assertFileExists($requestFile, "매핑된 FormRequest 파일이 없습니다: {$requestPath}");
$repositoryColumns = $this->extractRepositoryColumns((string) file_get_contents($repositoryFile));
$gateColumns = $this->extractGateColumns((string) file_get_contents($requestFile));
$this->assertNotEmpty($repositoryColumns, "정렬 허용 컬럼을 추출하지 못했습니다: {$repositoryPath}");
$this->assertNotEmpty($gateColumns, "sort_by 허용 값을 추출하지 못했습니다: {$requestPath}");
$missing = array_diff($gateColumns, $repositoryColumns);
$this->assertSame(
[],
array_values($missing),
"{$repositoryPath} 의 정렬 허용 목록이 게이트({$requestPath})보다 좁습니다. "
."검증을 통과한 정렬이 조용히 기본값으로 되돌아갑니다.\n 누락: ".implode(', ', $missing)
);
}
}
@@ -0,0 +1,91 @@
# audit:allow test-scenario-coverage reason: 이슈 #492(공개 #74) 깊은 OFFSET 목록 페이지네이션 SSoT. axes cross product(수백 조합 × 26개 호출처)는 docblock 전수 @scenario 매핑이 비현실적이라 면제하고, 회귀 가드는 test_files(트레이트 단위 + 호출 계약 전수 스캔 + 도메인별 저장소 회귀 + Playwright E2E)로 커버한다. 대용량 축(scale)은 scenario-scale-axis-required 룰이 별도 강제(면제 대상 아님) — scale.assert 는 @scale 마킹으로 전수 커버.
feature: deep_offset_pagination
description: |
목록 페이지네이션이 뒤쪽 페이지로 갈수록 선형으로 느려지던 것을, 지연 조인(deferred join)
2단계 조회로 재설계한다. `OFFSET n` 은 건너뛸 n 건도 실제로 읽으며, 목록 SELECT 에 넓은
컬럼(text/longText/JSON)이 있으면 그 n 건의 넓은 컬럼까지 읽힌다. InnoDB 는 행 밖 오버플로
페이지에 저장된 값을 앞부분만 필요해도 페이지째 읽으므로 비용이 그대로 누적된다.
핵심 설계:
- inner: 필터/정렬만으로 **키 컬럼만** 조회해 이번 페이지의 ID 집합을 구한다.
- outer: 그 ID 집합에 대해서만 목록 컬럼과 관계를 조회한다 — 넓은 컬럼을 읽는 행 수가
OFFSET 과 무관하게 페이지 크기로 고정된다.
- 정렬은 닫힌 집합(ResolvesSortSpec)이어야 한다. 인덱스 없는 컬럼 정렬은 inner 도 전체
스캔하므로 개선 폭이 보장되지 않는다.
- 키 컬럼을 정렬 말미에 자동으로 덧붙여 전순서를 만든다 — 동률 정렬에서 페이지 경계가
흔들려 행이 중복/누락되는 것을 막는다.
- 총 건수는 Laravel paginate() 와 같은 집계 경로(getCountForPagination)를 쓴다. count() 는
groupBy/having 쿼리에서 첫 그룹의 행 수를 총 건수로 돌려준다.
- `SUBSTRING(col, 1, N)` 은 프루닝으로 인정하지 않는다 — 오버플로 페이지 읽기가 그대로
발생하므로 잘라내기는 outer 에서만 수행한다.
axes:
page_position: [first, middle, last]
sort_column: [key, indexed_non_key, tied_values]
total_source: [counted, injected_cache, simple_no_count]
soft_delete: [default_excluded, with_trashed]
query_shape: [flat, joined, grouped]
relations: [none, eager_load, with_count]
filter: [none, search, scoped]
columns: [pruned, all]
exclusions:
- { total_source: simple_no_count, page_position: last, reason: "simplePaginate 는 총 건수를 세지 않아 마지막 페이지 개념이 없다 — hasMorePages 판정으로 대체" }
- { query_shape: grouped, total_source: simple_no_count, reason: "그룹 쿼리의 다음 페이지 판정은 총 건수 경로와 무관 — 그룹 수 정확성이 검증 대상" }
- { soft_delete: with_trashed, query_shape: grouped, reason: "그룹 목록(회원 활동)에 휴지통 조회 진입점이 없다" }
effects:
# ── 조회 구조 (P0) ──
- inner_selects_key_column_only
- inner_excludes_wide_columns_from_offset_scan
- outer_filters_by_id_set_without_offset
- relations_eager_loaded_on_outer_only
- with_count_applied_on_outer_only
- empty_id_set_skips_outer_query
# ── 총 건수 (P0) ──
- injected_total_skips_count_query
- simple_mode_skips_count_query
- grouped_query_total_counts_groups_not_first_group_rows
- filtered_query_total_reflects_filters
# ── 페이지 경계 정합 (P0) ──
- key_column_appended_to_sort_for_total_order
- pages_do_not_overlap_or_drop_rows
- outer_result_order_matches_inner_order
- preserve_id_order_restores_inner_sequence
- simple_mode_reports_last_page_without_next
# ── 스코프 보존 (P1) ──
- soft_deleted_rows_stay_excluded
- with_trashed_scope_is_preserved
- query_filters_are_preserved_on_both_stages
- self_scoped_list_returns_only_own_rows
- comments_of_soft_deleted_parents_stay_excluded
# ── 페이지네이터 계약 (P1) ──
- paginator_supports_query_string_appending
- custom_page_name_is_reflected_in_links
# ── 호출 계약 (P1) ──
- every_call_site_declares_columns
- every_call_site_declares_non_empty_sort
# ── 정렬 화이트리스트 (P0) ──
- sort_column_resolved_from_closed_set
- unknown_sort_column_falls_back_to_default
# scale: 대용량 회귀 축. block-array of flow objects (내장 fallback 파서 제약 — flow 객체만 중첩 파싱)
scale:
- { n: 200000, dataset: board_posts, assert: [deep_offset_bounded_growth, id_only_inner_query, no_wide_column_in_offset_scan] }
test_files:
# 코어 — 트레이트 단위 (조회 구조 / 총 건수 / 페이지 경계 / 스코프)
- tests/Unit/Repositories/Concerns/PaginatesWithDeferredJoinTest.php
- tests/Unit/Repositories/Concerns/ResolvesSortSpecTest.php
# 코어 — 호출 계약 전수 스캔 (호출처가 늘어나도 자동 편입)
- tests/Unit/Repositories/Concerns/DeferredJoinCallSiteContractTest.php
# 게시판 — 공지 병합 / 답글 트리 / 소프트 삭제 / 정렬 경계
- modules/_bundled/sirsoft-board/tests/Unit/Repositories/PostListDeferredJoinTest.php
# 게시판 — 삭제된 글의 댓글 제외 / 캐시 total / 검색 총 건수
- modules/_bundled/sirsoft-board/tests/Unit/Repositories/CommentListDeferredJoinTest.php
# 이커머스 — 주문 목록 소프트 삭제 + 페이지 경계
- modules/_bundled/sirsoft-ecommerce/tests/Feature/Http/Controllers/Admin/OrderListDeferredJoinTest.php
# 브라우저 — 마지막 페이지 다음 버튼 / 페이지 이동 후 목록 정합
- tests/Playwright/specs/pagination/deep-offset-list.spec.ts