Allow instantiation with existing PDOs

This commit is contained in:
Joby Elliott 2019-03-13 09:50:51 -06:00
parent 7f70b8839e
commit 385f6c2b89
4 changed files with 46 additions and 16 deletions

View file

@ -21,4 +21,19 @@ class DriverFactory
return null;
}
}
public static function factoryFromPDO(\PDO &$pdo, string $type = null) : ?Drivers\DSODriverInterface
{
if (!$type) {
$type = $pdo->getAttribute(\PDO::ATTR_DRIVER_NAME);
}
$type = strtolower($type);
if ($class = @static::$map[$type]) {
$f = new $class();
$f->pdo($pdo);
return $f;
} else {
return null;
}
}
}

View file

@ -12,13 +12,24 @@ abstract class AbstractDriver implements DSODriverInterface
public $pdo;
const EXTENSIBLE_VIRTUAL_COLUMNS = true;
public function __construct(string $dsn, string $username=null, string $password=null, array $options=null)
public function __construct(string $dsn=null, string $username=null, string $password=null, array $options=null)
{
if (!$this->pdo = new \PDO($dsn, $username, $password, $options)) {
throw new \Exception("Error creating PDO connection");
if ($dsn) {
if (!($pdo = new \PDO($dsn, $username, $password, $options))) {
throw new \Exception("Error creating PDO connection");
}
$this->pdo($pdo);
}
}
public function &pdo(\PDO &$pdo=null) : ?\PDO
{
if ($pdo) {
$this->pdo = $pdo;
}
return $this->pdo;
}
protected function expandPaths($value)
{
if ($value === null) {

View file

@ -7,7 +7,8 @@ use Destructr\Search;
interface DSODriverInterface
{
public function __construct(string $dsn, string $username=null, string $password=null, array $options=null);
public function __construct(string $dsn=null, string $username=null, string $password=null, array $options=null);
public function &pdo(\PDO &$pdo=null) : ?\PDO;
public function createTable(string $table, array $virtualColumns) : bool;
public function select(string $table, Search $search, array $params);

View file

@ -16,19 +16,22 @@ use Destructr\Factory;
*/
class SQLiteDriver extends AbstractLegacyDriver
{
public function __construct(string $dsn, string $username=null, string $password=null, array $options=null)
public function &pdo(\PDO &$pdo=null) : ?\PDO
{
parent::__construct($dsn, $username, $password, $options);
/*
What we're doing here is adding a custom function to SQLite so that it
can extract JSON values. It's not fast, but it does let us use JSON
fairly seamlessly.
*/
$this->pdo->sqliteCreateFunction(
'DESTRUCTR_JSON_EXTRACT',
'\\Destructr\\LegacyDrivers\\SQLiteDriver::JSON_EXTRACT',
2
);
if ($pdo) {
$this->pdo = $pdo;
/*
What we're doing here is adding a custom function to SQLite so that it
can extract JSON values. It's not fast, but it does let us use JSON
fairly seamlessly.
*/
$this->pdo->sqliteCreateFunction(
'DESTRUCTR_JSON_EXTRACT',
'\\Destructr\\LegacyDrivers\\SQLiteDriver::JSON_EXTRACT',
2
);
}
return $this->pdo;
}
public static function JSON_EXTRACT($json, $path)