diff --git a/lib/Connection.php b/lib/Connection.php index 69e8a1b20..de2766a42 100644 --- a/lib/Connection.php +++ b/lib/Connection.php @@ -168,6 +168,7 @@ private static function load_adapter_class($adapter) * sqlite://../relative/path/to/file.db * sqlite://unix(/absolute/path/to/file.db) * sqlite://windows(c%2A/absolute/path/to/file.db) + * sqlite://:memory: * * * @param string $connection_url A connection URL @@ -177,6 +178,9 @@ public static function parse_connection_url($connection_url) { $url = @parse_url($connection_url); + if ($url['scheme'] == "sqlite" && $url['host'] == ":memory") + $url['host'] = ":memory:"; + if (!isset($url['host'])) throw new DatabaseException('Database host must be specified in the connection string. If you want to specify an absolute filename, use e.g. sqlite://unix(/path/to/file)'); diff --git a/lib/adapters/SqliteAdapter.php b/lib/adapters/SqliteAdapter.php index 0917043be..581cd28c0 100644 --- a/lib/adapters/SqliteAdapter.php +++ b/lib/adapters/SqliteAdapter.php @@ -15,13 +15,17 @@ class SqliteAdapter extends Connection { static $datetime_format = 'Y-m-d H:i:s'; + private static $cached_connection; protected function __construct($info) { - if (!file_exists($info->host)) + if ($info->host != ":memory:" && !file_exists($info->host)) throw new DatabaseException("Could not find sqlite db: $info->host"); - $this->connection = new PDO("sqlite:$info->host",null,null,static::$PDO_OPTIONS); + if (self::$cached_connection == null) { + self::$cached_connection = new PDO("sqlite:$info->host",null,null,static::$PDO_OPTIONS); + } + $this->connection = self::$cached_connection; } public function limit($sql, $offset, $limit) diff --git a/test/SqliteAdapterMemoryTest.php b/test/SqliteAdapterMemoryTest.php new file mode 100644 index 000000000..0106c3823 --- /dev/null +++ b/test/SqliteAdapterMemoryTest.php @@ -0,0 +1,30 @@ +get_connections(); + $connections['sqlite'] = 'sqlite://:memory:'; + ActiveRecord\Config::instance()->set_connections($connections); + + parent::set_up(); + } + + public function testConnectToMemoryDatabaseShouldNotCreateDbFile() + { + try + { + ActiveRecord\Connection::instance("sqlite://:memory:"); + $this->assertFalse(file_exists(__DIR__ . "/" . ":memory:")); + } + catch (ActiveRecord\DatabaseException $e) + { + $this->fail("could not open connection to :memory: database"); + } + } + +} +?>