<?php
require __DIR__ . '/bootstrap/autoload.php';
$app = require_once __DIR__ . '/bootstrap/app.php';
$app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();

use Illuminate\Support\Facades\DB;

$u = \Backend\Models\User::find(1);

$report = function (string $tag, array $log): void {
    foreach ($log as $q) {
        if (strpos($q['query'], 'system_files') === false) {
            continue;
        }
        echo "$tag" . "_SQL=" . $q['query'] . "\n";
        foreach ($q['bindings'] as $i => $b) {
            if (!is_object($b)) {
                echo "  bind[$i] type=" . gettype($b) . " val=" . var_export($b, true) . "\n";
            }
        }
        foreach (DB::select('EXPLAIN ' . $q['query'], $q['bindings']) as $row) {
            $r = (array) $row;
            echo "  EXPLAIN type=" . $r['type'] . " key=" . ($r['key'] ?? 'NULL') . " rows=" . $r['rows'] . "\n";
        }
    }
};

DB::flushQueryLog();
DB::enableQueryLog();
$u->avatar()->getResults();
$report('LAZY', DB::getQueryLog());

DB::flushQueryLog();
\Backend\Models\User::with('avatar')->where('id', 1)->get();
$report('EAGER', DB::getQueryLog());
DB::disableQueryLog();

$t = microtime(true);
for ($i = 0; $i < 50; $i++) {
    $u->avatar()->getResults();
}
printf("LAZY_AVG_MS=%.3f\n", (microtime(true) - $t) / 50 * 1000);

$t = microtime(true);
for ($i = 0; $i < 30; $i++) {
    \Backend\Models\User::with('avatar')->where('id', 1)->get();
}
printf("EAGER_AVG_MS=%.3f\n", (microtime(true) - $t) / 30 * 1000);
