Driver.php 2.18 KB
Newer Older
1 2
<?php

3
namespace Doctrine\DBAL\Driver\PDOSqlite;
4

5
use Doctrine\DBAL\DBALException;
6
use Doctrine\DBAL\Driver\AbstractSQLiteDriver;
Steve Müller's avatar
Steve Müller committed
7
use Doctrine\DBAL\Driver\PDOConnection;
8
use Doctrine\DBAL\Platforms\SqlitePlatform;
9
use PDOException;
10
use function array_merge;
11

12 13 14
/**
 * The PDO Sqlite driver.
 */
15
class Driver extends AbstractSQLiteDriver
16
{
17
    /** @var mixed[] */
18
    protected $_userDefinedFunctions = [
19 20 21
        'sqrt' => ['callback' => [SqlitePlatform::class, 'udfSqrt'], 'numArgs' => 1],
        'mod'  => ['callback' => [SqlitePlatform::class, 'udfMod'], 'numArgs' => 2],
        'locate'  => ['callback' => [SqlitePlatform::class, 'udfLocate'], 'numArgs' => -1],
22
    ];
23

24
    /**
Benjamin Morel's avatar
Benjamin Morel committed
25
     * {@inheritdoc}
26
     */
27
    public function connect(array $params, $username = null, $password = null, array $driverOptions = [])
28
    {
29 30
        if (isset($driverOptions['userDefinedFunctions'])) {
            $this->_userDefinedFunctions = array_merge(
31 32 33
                $this->_userDefinedFunctions,
                $driverOptions['userDefinedFunctions']
            );
34 35 36
            unset($driverOptions['userDefinedFunctions']);
        }

37
        try {
38
            $connection = new PDOConnection(
39 40 41 42 43 44 45 46
                $this->_constructPdoDsn($params),
                $username,
                $password,
                $driverOptions
            );
        } catch (PDOException $ex) {
            throw DBALException::driverException($this, $ex);
        }
47

48 49
        $pdo = $connection->getWrappedConnection();

50
        foreach ($this->_userDefinedFunctions as $fn => $data) {
51 52 53
            $pdo->sqliteCreateFunction($fn, $data['callback'], $data['numArgs']);
        }

54
        return $connection;
55
    }
56

57 58 59
    /**
     * Constructs the Sqlite PDO DSN.
     *
60
     * @param mixed[] $params
Benjamin Morel's avatar
Benjamin Morel committed
61 62
     *
     * @return string The DSN.
63 64 65 66 67 68
     */
    protected function _constructPdoDsn(array $params)
    {
        $dsn = 'sqlite:';
        if (isset($params['path'])) {
            $dsn .= $params['path'];
Steve Müller's avatar
Steve Müller committed
69
        } elseif (isset($params['memory'])) {
70 71
            $dsn .= ':memory:';
        }
72

73 74
        return $dsn;
    }
75

Benjamin Morel's avatar
Benjamin Morel committed
76 77
    /**
     * {@inheritdoc}
78 79
     *
     * @deprecated
Benjamin Morel's avatar
Benjamin Morel committed
80
     */
81 82 83 84
    public function getName()
    {
        return 'pdo_sqlite';
    }
85
}