Skip to content
Search

Last updated

Trace SQL queries in PHP: find the slow PostgreSQL query of a script

Let's say a nightly script builds a sales report: it reads a customer, sums up the orders of the country, and saves the result in a transaction. The script got slower every month, and now somebody asks which query it is.

These scripts need a PostgreSQL database, so they run only on your machine, not in the playground.

Time SQL queries in PHP by hand

The first idea is always a timer around the query we suspect.

<?php

declare(strict_types=1);

use function Flow\PostgreSql\DSL\{pgsql_client, pgsql_connection};

require __DIR__ . '/vendor/autoload.php';

$client = pgsql_client(pgsql_connection('host=localhost port=5432 dbname=shop user=postgres password=postgres'));

$start = hrtime(true);
$country = $client->fetchOne('SELECT country FROM customers WHERE id = $1', [42]);
printf("customer: %.1fms\n", (hrtime(true) - $start) / 1e6);
customer: 1.8ms

It works, for the one query we wrapped.

Why timers around queries are not enough

The script has four queries, so it needs four timers, and the next query somebody adds has none. A timer also knows nothing about the transaction around the queries, and it says nothing when a query fails.

We want every query measured in the place where all of them pass: the database client.

Trace every query of the PostgreSQL client

flow-php/telemetry is an independent implementation of OpenTelemetry, written in PHP, and it is not a wrapper around the official SDK. The client needs PHP 8.3 or newer and the pgsql extension.

composer require flow-php/postgresql flow-php/telemetry flow-php/etl
<?php

declare(strict_types=1);

use function Flow\ETL\DSL\clock;
use function Flow\PostgreSql\DSL\{pgsql_client, pgsql_connection, postgresql_telemetry_config, traceable_postgresql_client};
use function Flow\Telemetry\DSL\{
    console_exporter,
    memory_context_storage,
    pass_through_span_processor,
    resource,
    telemetry,
    tracer_provider,
};

require __DIR__ . '/vendor/autoload.php';

$telemetry = telemetry(
    resource(['service.name' => 'nightly-report']),
    tracer_provider(pass_through_span_processor(console_exporter(colors: false)), clock(), memory_context_storage()),
);

$client = traceable_postgresql_client(
    pgsql_client(pgsql_connection('host=localhost port=5432 dbname=shop user=postgres password=postgres')),
    postgresql_telemetry_config($telemetry, clock()),
);

$telemetry->tracer('report')->trace('nightly-report', static function () use ($client): void {
    $country = $client->fetchOne('SELECT country FROM customers WHERE id = $1', [42]);
    $total = $client->fetchScalar('SELECT SUM(amount) FROM orders WHERE country = $1', [$country['country']]);

    $client->transaction(static function () use ($client, $country, $total): void {
        $client->execute('DELETE FROM report WHERE country = $1', [$country['country']]);
        $client->execute('INSERT INTO report (country, total) VALUES ($1, $2)', [$country['country'], $total]);
    });
});

The script prints six spans. These are the lines that matter, with the rest cut:

| SPAN: SELECT customers                                   Duration: 8.38ms
|   db.query.text = SELECT country FROM customers WHERE id = $1
| SPAN: SELECT orders                                      Duration: 50.27ms
|   db.query.text = SELECT SUM(amount) FROM orders WHERE country = $1
| SPAN: DELETE report                                      Duration: 1.04ms
|   db.query.text = DELETE FROM report WHERE country = $1
| SPAN: INSERT report                                      Duration: 402.00us
|   db.query.text = INSERT INTO report (country, total) VALUES ($1, $2)
| SPAN: BEGIN TRANSACTION                                  Duration: 5.41ms
| SPAN: nightly-report                                     Duration: 72.37ms

The script took 72ms, and 50ms of it is the sum over the orders table. That's our query.

The code of the report has no timer. One line changed: traceable_postgresql_client wraps the client, and every method of the client is traced, also for queries that somebody adds next month.

What a query span tells us

  • The name is the operation and the table, SELECT orders. It has no values in it, so a monitoring tool can group all runs of one query.
  • The SQL is there with $1 in place of the values. The data of our customers doesn't leave the database.
  • The transaction is one span, BEGIN TRANSACTION, and the two queries inside are its children. We see how long the transaction was open, not only how long its queries took.
  • An error sets the status of the span, with the SQLSTATE code of PostgreSQL.

All spans have the trace id of nightly-report, because the client found that span open. In a web application the same happens with the span of the request.

What to set for query tracing

postgresql_telemetry_options is the third argument of the config, and none of it is needed to start:

Option Default What it does
maxQueryLength 1000 Cuts the SQL text in the span
includeParameters false Adds the bound values. They can be personal data, so leave it off
transactionSpans GROUPED One span for a whole transaction, or PER_OPERATION, or OFF
collectMetrics true A histogram of query durations, when a meter provider is configured
logQueries false Writes each query to the telemetry logger

Where to go from here

The console is for our machine. On a server the spans go to a collector: see send PHP traces over OTLP. With Doctrine in a Symfony application the same idea needs no code at all: see find slow Doctrine queries in Symfony. The basics of spans are in the guide about tracing in PHP.

Found a typo or an outdated section? Edit this guide on GitHub

scroll back to top