<?php /** @noinspection PhpUnused */

namespace apexl\Vault\operators\drivers;

use apexl\Aura\SqlQuery\QueryFactory;
use apexl\Vault\exceptions\SqliteUnsupportedException;
use PDO as PdoConnection;

class sqlite extends mysql
{
    public function describe(string $table): sqlite
    {
        return $this->executeSql(sprintf('DESCRIBE %s', $table));
    }

    /**
     * Not supported on sqlite. The parent (mysql) upsert emits MySQL-only
     * `ON DUPLICATE KEY UPDATE`; sqlite needs `ON CONFLICT ... DO UPDATE`,
     * which the Aura\SqlQuery\Sqlite\Insert builder cannot generate — and
     * inheriting the parent would be worse: its `instanceof Mysql\Insert`
     * guard never matches sqlite's query object, so the clause would be
     * dropped silently and upsert() would behave as a plain insert().
     *
     * @throws SqliteUnsupportedException always
     */
    public function upsert(string $table, array $updateColumns = []): mysql
    {
        throw new SqliteUnsupportedException(
            'upsert() is not supported by the sqlite driver: Aura\SqlQuery\Sqlite\Insert '
            . 'cannot generate ON CONFLICT ... DO UPDATE. Use insert() with an existence '
            . 'pre-check, or executeSql() with hand-written ON CONFLICT SQL.'
        );
    }

    /**
     * Must return the apexl QueryFactory subclass: the parent (mysql)
     * declaration narrowed its return type to apexl\Aura\SqlQuery\QueryFactory,
     * and returning the plain Aura base here is a covariance violation — PHP
     * fatals at class-load time, which made this driver unloadable until now.
     * The 'sqlite' driver string still selects Aura's Sqlite query objects.
     */
    protected function createQueryFactory(): QueryFactory
    {
        return new QueryFactory('sqlite');
    }

    protected function makeConnection(): PdoConnection
    {
        $pdo = new PdoConnection(
            'sqlite:file::memory:?cache=shared',
        );
        $pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
        return $pdo;
    }

}
