Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

API Upgraded module to use new database ORM #3

Merged
merged 1 commit into from
Jul 10, 2014
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 1 addition & 35 deletions _config.php
Original file line number Diff line number Diff line change
@@ -1,37 +1,3 @@
<?php

Deprecation::notification_version('1.3.0', 'sqlite3');

$classes = array('SQLiteDatabase', 'SQLite3Database', 'SQLitePDODatabase');

global $databaseConfig;
if(defined('SS_DATABASE_CLASS') && in_array(SS_DATABASE_CLASS, $classes)) {
$databaseConfig['type'] = SS_DATABASE_CLASS;
}

if(in_array($databaseConfig['type'], $classes)) {
if(empty($databaseConfig['path'])) {
// default the database path to a location in assets
$databaseConfig['path'] = defined('SS_SQLITE_DATABASE_PATH') && SS_SQLITE_DATABASE_PATH ? SS_SQLITE_DATABASE_PATH : ASSETS_PATH . '/.sqlitedb/';
}

$databaseConfig['database'] = (defined('SS_DATABASE_PREFIX') ? SS_DATABASE_PREFIX : '') . $databaseConfig['database'] . (defined('SS_DATABASE_SUFFIX') ? SS_DATABASE_SUFFIX : '');

if(empty($databaseConfig['key'])) {
$databaseConfig['key'] = defined('SS_SQLITE_DATABASE_KEY') && SS_SQLITE_DATABASE_KEY ? SS_SQLITE_DATABASE_KEY : 'SQLite3DatabaseKey';
}

/**
* set pragma values on the connection.
* @see http://www.sqlite.org/pragma.html
*/
SQLite3Database::$default_pragma['encoding'] = '"UTF-8"';
SQLite3Database::$default_pragma['locking_mode'] = 'NORMAL';

// The SQLite3 class is available in PHP 5.3 and newer
if(class_exists('SQLite3') && $databaseConfig['type'] != 'SQLitePDODatabase') {
$databaseConfig['type'] = 'SQLite3Database';
} else {
$databaseConfig['type'] = 'SQLitePDODatabase';
}
}
Deprecation::notification_version('1.4.0', 'sqlite3');
29 changes: 29 additions & 0 deletions _config/connectors.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
---
name: sqlite3connectors
---
Injector:
SQLite3PDODatabase:
class: 'SQLite3Database'
properties:
connector: %$PDOConnector
schemaManager: %$SQLite3SchemaManager
queryBuilder: %$SQLite3QueryBuilder
SQLite3Database:
class: 'SQLite3Database'
properties:
connector: %$SQLite3Connector
schemaManager: %$SQLite3SchemaManager
queryBuilder: %$SQLite3QueryBuilder
# Legacy connector names
SQLiteDatabase:
class: 'SQLite3Database'
properties:
connector: %$SQLite3Connector
schemaManager: %$SQLite3SchemaManager
queryBuilder: %$SQLite3QueryBuilder
SQLitePDODatabase:
class: 'SQLite3Database'
properties:
connector: %$SQLite3Connector
schemaManager: %$SQLite3SchemaManager
queryBuilder: %$SQLite3QueryBuilder
4 changes: 4 additions & 0 deletions _config/sqllite3.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
SQLLite3Database:
# Extension used to distinguish between sqllite database files and other files
# Required to handle multiple databases
database_extension: '.sqlite'
14 changes: 14 additions & 0 deletions _configure_database.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<?php

// Script called from ConfigureFromEnv.php
global $databaseConfig;
if(strpos($databaseConfig['type'], 'SQLite') === 0) {

if(defined('SS_SQLITE_DATABASE_PATH')) {
$databaseConfig['path'] = SS_SQLITE_DATABASE_PATH;
}

if(defined('SS_SQLITE_DATABASE_KEY')) {
$databaseConfig['key'] = SS_SQLITE_DATABASE_KEY;
}
}
45 changes: 45 additions & 0 deletions _register_database.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
<?php

$sqliteDatabaseAdapterRegistryFields = array(
'path' => array(
'title' => 'Directory path<br /><small>Absolute path to directory, writeable by the webserver user.<br />'
. 'Recommended to be outside of your webroot</small>',
'default' => dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . 'assets' . DIRECTORY_SEPARATOR . '.sqlitedb'
),
'database' => array(
'title' => 'Database filename (extension .sqlite)',
'default' => 'database.sqlite'
)
);

// Basic SQLLite3 Database
DatabaseAdapterRegistry::register(
array(
'class' => 'SQLite3Database',
'title' => 'SQLite 3.3+ (using SQLite3)',
'helperPath' => dirname(__FILE__).'/code/SQLiteDatabaseConfigurationHelper.php',
'supported' => class_exists('SQLite3'),
'missingExtensionText' => 'The <a href="http://php.net/manual/en/book.sqlite3.php">SQLite3</a>
PHP Extension is not available. Please install or enable it of them and refresh this page.',
'fields' => array_merge($sqliteDatabaseAdapterRegistryFields, array('key' => array(
'title' => 'Encryption key<br><small>This function is experimental and requires configuration of an '
. 'encryption module</small>',
'default' => ''
)))
)
);

// PDO database
DatabaseAdapterRegistry::register(
array(
'class' => 'SQLite3PDODatabase',
'title' => 'SQLite 3.3+ (using PDO)',
'helperPath' => dirname(__FILE__).'/code/SQLiteDatabaseConfigurationHelper.php',
'supported' => (class_exists('PDO') && in_array('sqlite', PDO::getAvailableDrivers())),
'missingExtensionText' =>
'Either the <a href="http://php.net/manual/en/book.pdo.php">PDO Extension</a> or the
<a href="http://php.net/manual/en/book.sqlite3.php">SQLite3 PDO Driver</a>
are unavailable. Please install or enable these and refresh this page.',
'fields' => $sqliteDatabaseAdapterRegistryFields
)
);
187 changes: 187 additions & 0 deletions code/SQLite3Connector.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,187 @@
<?php

/**
* SQLite connector class
*
* @package SQLite3
*/
class SQLite3Connector extends DBConnector {

/**
* The name of the database.
*
* @var string
*/
protected $databaseName;

/**
* Connection to the DBMS.
*
* @var SQLite3
*/
protected $dbConn;

public function connect($parameters, $selectDB = false) {
$file = $parameters['filepath'];
$this->dbConn = empty($parameters['key'])
? new SQLite3($file, SQLITE3_OPEN_READWRITE | SQLITE3_OPEN_CREATE)
: new SQLite3($file, SQLITE3_OPEN_READWRITE | SQLITE3_OPEN_CREATE, $parameters['key']);
$this->dbConn->busyTimeout(60000);
$this->databaseName = $parameters['database'];
}

public function affectedRows() {
return $this->dbConn->changes();
}

public function getGeneratedID($table) {
return $this->dbConn->lastInsertRowID();
}

public function getLastError() {
$message = $this->dbConn->lastErrorMsg();
return $message === 'not an error' ? null : $message;
}

public function getSelectedDatabase() {
return $this->databaseName;
}

public function getVersion() {
$version = SQLite3::version();
return trim($version['versionString']);
}

public function isActive() {
return $this->databaseName && $this->dbConn;
}

/**
* Prepares the list of parameters in preparation for passing to mysqli_stmt_bind_param
*
* @param array $parameters List of parameters
* @return array List of parameters types and values
*/
public function parsePreparedParameters($parameters) {
$values = array();
foreach($parameters as $value) {
$phpType = gettype($value);
$sqlType = null;

// Allow overriding of parameter type using an associative array
if($phpType === 'array') {
$phpType = $value['type'];
$value = $value['value'];
}

// Convert php variable type to one that makes mysqli_stmt_bind_param happy
// @see http://www.php.net/manual/en/mysqli-stmt.bind-param.php
switch($phpType) {
case 'boolean':
case 'integer':
$sqlType = SQLITE3_INTEGER;
break;
case 'float': // Not actually returnable from gettype
case 'double':
$sqlType = SQLITE3_FLOAT;
break;
case 'object': // Allowed if the object or resource has a __toString method
case 'resource':
case 'string':
$sqlType = SQLITE3_TEXT;
break;
case 'NULL':
$sqlType = SQLITE3_NULL;
break;
case 'blob':
$sqlType = SQLITE3_BLOB;
break;
case 'array':
case 'unknown type':
default:
user_error("Cannot bind parameter \"$value\" as it is an unsupported type ($phpType)", E_USER_ERROR);
break;
}
$values[] = array(
'type' => $sqlType,
'value' => $value
);
}
return $values;
}

public function preparedQuery($sql, $parameters, $errorLevel = E_USER_ERROR) {
// Check if we should only preview this query
if ($this->previewWrite($sql)) return;

// Type check, identify, and prepare parameters for passing to the statement bind function
$parsedParameters = $this->parsePreparedParameters($parameters);

// Benchmark query
$conn = $this->dbConn;
$handle = $this->benchmarkQuery($sql, function($sql) use($conn, $parsedParameters) {

// Prepare statement
$statement = @$conn->prepare($sql);
if(empty($statement)) return null;

// Bind all variables
for($i = 0; $i < count($parsedParameters); $i++) {
$value = $parsedParameters[$i]['value'];
$type = $parsedParameters[$i]['type'];
$statement->bindValue($i+1, $value, $type);
}

// Run
return $statement->execute();
});

// Check for errors
if (!$handle) {
$values = $this->parameterValues($parameters);
$this->databaseError($this->getLastError(), $errorLevel, $sql, $values);
return null;
}

return new SQLite3Query($this, $handle);
}

public function query($sql, $errorLevel = E_USER_ERROR) {
// Check if we should only preview this query
if ($this->previewWrite($sql)) return;

// Benchmark query
$conn = $this->dbConn;
$handle = $this->benchmarkQuery($sql, function($sql) use($conn) {
return @$conn->query($sql);
});

// Check for errors
if (!$handle) {
$this->databaseError($this->getLastError(), $errorLevel, $sql);
return null;
}

return new SQLite3Query($this, $handle);
}

public function quoteString($value) {
return "'".$this->escapeString($value)."'";
}

public function escapeString($value) {
return $this->dbConn->escapeString($value);
}

public function selectDatabase($name) {
if($name !== $this->databaseName) {
user_error("SQLite3Connector can't change databases. Please create a new database connection", E_USER_ERROR);
}
return true;
}

public function unloadDatabase() {
$this->dbConn->close();
$this->databaseName = null;
}
}
Loading