made compatible with WP 3.9 and fixed bugs

git-svn-id: https://plugins.svn.wordpress.org/sqlite-integration/trunk@895495 b8457f37-d9ea-0310-8a92-e5e31aec5664
This commit is contained in:
kjmtsh 2014-04-17 02:45:32 +00:00
parent f0a5b97f3c
commit 862acb1899
10 changed files with 290 additions and 139 deletions

2
db.php
View File

@ -30,7 +30,7 @@ if (!defined('ABSPATH')) { // Oh, you are not WordPress!
* define('USE_MYSQL', false); * define('USE_MYSQL', false);
* </code> * </code>
*/ */
if (defined('USE_MYSQL') && USE_MYSQL === true) return; if (defined('USE_MYSQL') && USE_MYSQL) return;
function pdo_log_error($message, $data = null) { function pdo_log_error($message, $data = null) {

View File

@ -77,6 +77,15 @@ class PDODB extends wpdb {
if ( ! isset( $collate ) ) if ( ! isset( $collate ) )
$collate = $this->collate; $collate = $this->collate;
} }
/**
* Method to dummy out wpdb::set_sql_mode()
*
* @see wpdb::set_sql_mode()
*/
function set_sql_mode($modes = array()) {
unset($modes);
return;
}
/** /**
* Method to select the database connection. * Method to select the database connection.
* *
@ -90,7 +99,13 @@ class PDODB extends wpdb {
$this->ready = true; $this->ready = true;
return; return;
} }
/**
* Method to dummy out wpdb::_weak_escape()
*
*/
function _weak_escape($string) {
return addslashes($string);
}
/** /**
* Method to escape characters. * Method to escape characters.
* *
@ -172,7 +187,7 @@ class PDODB extends wpdb {
* *
* @see wpdb::db_connect() * @see wpdb::db_connect()
*/ */
function db_connect() { function db_connect($allow_bail=true) {
if (WP_DEBUG) { if (WP_DEBUG) {
$this->dbh = new PDOEngine(); $this->dbh = new PDOEngine();
} else { } else {
@ -187,7 +202,13 @@ class PDODB extends wpdb {
} }
$this->ready = true; $this->ready = true;
} }
/**
* Method to dummy out wpdb::check_connection()
*
*/
function check_connection($allow_bail=true) {
return true;
}
/** /**
* Method to execute the query. * Method to execute the query.
* *
@ -243,6 +264,19 @@ class PDODB extends wpdb {
} }
return $return_val; return $return_val;
} }
/**
*
*/
private function _do_query($query) {
if (defined('SAVEQUERIES') && SAVEQUERIES) {
$this->timer_start();
}
$this->result = $this->dbh->query($query);
$this->num_queries++;
if (defined('SAVEQUERIES') && SAVEQUERIES) {
$this->queries[] = array($query, $this->timer_stop(), $this->get_caller());
}
}
/** /**
* Method to set the class variable $col_info. * Method to set the class variable $col_info.
* *
@ -299,5 +333,7 @@ class PDODB extends wpdb {
if (!isset($wpdb)) { if (!isset($wpdb)) {
global $wpdb; global $wpdb;
$wpdb = new PDODB(); $wpdb = new PDODB();
$is_enabled_foreign_keys = @$wpdb->get_var('PRAGMA foreign_keys');
if ($is_enabled_foreign_keys == '0') @$wpdb->query('PRAGMA foreign_keys = ON');
} }
?> ?>

View File

@ -170,7 +170,7 @@ class PDOEngine extends PDO {
} }
/** /**
* Function to initialize database, executed in the contructor. * Method to initialize database, executed in the contructor.
* *
* It checks if there's a database directory and database file, creates the tables, * It checks if there's a database directory and database file, creates the tables,
* and binds the user defined function to the pdo object. * and binds the user defined function to the pdo object.
@ -232,7 +232,7 @@ class PDOEngine extends PDO {
} }
/** /**
* This function makes database direcotry and .htaccess file. * This method makes database direcotry and .htaccess file.
* *
* It is executed only once when the installation begins. * It is executed only once when the installation begins.
*/ */
@ -243,15 +243,13 @@ class PDOEngine extends PDO {
if (!@mkdir(FQDBDIR, 0707, true)) { if (!@mkdir(FQDBDIR, 0707, true)) {
umask($u); umask($u);
$message = 'Unable to create the required directory! Please check your server settings.'; $message = 'Unable to create the required directory! Please check your server settings.';
echo $message; wp_die($message, 'Error!');
return false;
} }
} }
if (!is_writable(FQDBDIR)) { if (!is_writable(FQDBDIR)) {
umask($u); umask($u);
$message = 'Unable to create a file in the directory! Please check your server settings.'; $message = 'Unable to create a file in the directory! Please check your server settings.';
echo $message; wp_die($message, 'Error!');
return false;
} }
if (!is_file(FQDBDIR . '.htaccess')) { if (!is_file(FQDBDIR . '.htaccess')) {
$fh = fopen(FQDBDIR . '.htaccess', "w"); $fh = fopen(FQDBDIR . '.htaccess', "w");
@ -264,11 +262,22 @@ class PDOEngine extends PDO {
fwrite($fh, 'DENY FROM ALL'); fwrite($fh, 'DENY FROM ALL');
fclose($fh); fclose($fh);
} }
if (!is_file(FQDBDIR . 'index.php')) {
$fh = fopen(FQDBDIR . 'index.php', "w");
if (!$fh) {
umask($u);
$message = 'Unable to create a file in the directory! Please check your server settings.';
echo $message;
return false;
}
fwrite($fh, '<?php // Silence is gold. ?>');
fclose($fh);
}
umask($u); umask($u);
return true; return true;
} }
/** /**
* function to call install() function which overrides WordPress install(). * Method to call install() function which overrides WordPress install().
* *
* This function is executed only once during the installation process. * This function is executed only once during the installation process.
*/ */
@ -276,7 +285,7 @@ class PDOEngine extends PDO {
require_once PDODIR . 'install.php'; require_once PDODIR . 'install.php';
} }
/** /**
* Function to execute query(). * Method to execute query().
* *
* Divide the query types into seven different ones. That is to say: * Divide the query types into seven different ones. That is to say:
* *
@ -309,6 +318,9 @@ class PDOEngine extends PDO {
$this->set_error(__LINE__, __FUNCTION__, $bailoutString); $this->set_error(__LINE__, __FUNCTION__, $bailoutString);
} }
switch (strtolower($this->query_type)) { switch (strtolower($this->query_type)) {
case 'set':
$this->return_value = false;
break;
case 'foundrows': case 'foundrows':
$_column = array('FOUND_ROWS()' => ''); $_column = array('FOUND_ROWS()' => '');
$column = array(); $column = array();
@ -341,6 +353,9 @@ class PDOEngine extends PDO {
case 'show_variables': case 'show_variables':
$result = $this->show_variables_workaround($query); $result = $this->show_variables_workaround($query);
break; break;
case 'showstatus':
$result = $this->show_status_workaround($query);
break;
case 'drop_index': case 'drop_index':
$pattern = '/^\\s*(DROP\\s*INDEX\\s*.*?)\\s*ON\\s*(.*)/im'; $pattern = '/^\\s*(DROP\\s*INDEX\\s*.*?)\\s*ON\\s*(.*)/im';
if (preg_match($pattern, $query, $match)) { if (preg_match($pattern, $query, $match)) {
@ -372,7 +387,7 @@ class PDOEngine extends PDO {
return $this->return_value; return $this->return_value;
} }
/** /**
* Function to return inserted row id. * Method to return inserted row id.
* *
* @return unsigned integer * @return unsigned integer
*/ */
@ -380,7 +395,7 @@ class PDOEngine extends PDO {
return $this->last_insert_id; return $this->last_insert_id;
} }
/** /**
* Function to return the number of rows affected. * Method to return the number of rows affected.
* *
* @return unsigned integer * @return unsigned integer
*/ */
@ -388,7 +403,7 @@ class PDOEngine extends PDO {
return $this->affected_rows; return $this->affected_rows;
} }
/** /**
* Function to return the queried column names. * Method to return the queried column names.
* *
* These data are meaningless for SQLite. So they are dummy emulating * These data are meaningless for SQLite. So they are dummy emulating
* MySQL columns data. * MySQL columns data.
@ -444,7 +459,7 @@ class PDOEngine extends PDO {
} }
} }
/** /**
* Function to return the queried result data. * Method to return the queried result data.
* *
* @return mixed * @return mixed
*/ */
@ -452,7 +467,7 @@ class PDOEngine extends PDO {
return $this->results; return $this->results;
} }
/** /**
* Function to return the number of rows from the queried result. * Method to return the number of rows from the queried result.
* *
* @return unsigned integer * @return unsigned integer
*/ */
@ -460,7 +475,7 @@ class PDOEngine extends PDO {
return $this->num_rows; return $this->num_rows;
} }
/** /**
* Function to return the queried results according to the query types. * Method to return the queried results according to the query types.
* *
* @return mixed * @return mixed
*/ */
@ -468,7 +483,7 @@ class PDOEngine extends PDO {
return $this->return_value; return $this->return_value;
} }
/** /**
* Function to return error messages. * Method to return error messages.
* *
* @return string * @return string
*/ */
@ -500,7 +515,7 @@ class PDOEngine extends PDO {
} }
/** /**
* Function to return information about query string for debugging. * Method to return information about query string for debugging.
* *
* @return string * @return string
*/ */
@ -512,7 +527,7 @@ class PDOEngine extends PDO {
return $output; return $output;
} }
/** /**
* Function to clear previous data. * Method to clear previous data.
*/ */
private function flush(){ private function flush(){
$this->rewritten_query = ''; $this->rewritten_query = '';
@ -531,7 +546,7 @@ class PDOEngine extends PDO {
$this->param_num = 0; $this->param_num = 0;
} }
/** /**
* Function to include the apropreate class files. * Method to include the apropreate class files.
* *
* It is not a good habit to change the include files programatically. * It is not a good habit to change the include files programatically.
* Needs to be fixed some other way. * Needs to be fixed some other way.
@ -553,7 +568,7 @@ class PDOEngine extends PDO {
return $engine; return $engine;
} }
/** /**
* Function to create a PDO statement object from the query string. * Method to create a PDO statement object from the query string.
* *
* @return PDOStatement * @return PDOStatement
*/ */
@ -578,7 +593,7 @@ class PDOEngine extends PDO {
return $statement; return $statement;
} }
/** /**
* Function to execute PDO statement object. * Method to execute PDO statement object.
* *
* This function executes query and sets the variables to give back to WordPress. * This function executes query and sets the variables to give back to WordPress.
* The variables are class fields. So if success, no return value. If failure, it * The variables are class fields. So if success, no return value. If failure, it
@ -683,7 +698,7 @@ class PDOEngine extends PDO {
} }
} }
/** /**
* Function to extract field data to an array and prepare the query statement. * Method to extract field data to an array and prepare the query statement.
* *
* If original SQL statement is CREATE query, this function do nothing and return * If original SQL statement is CREATE query, this function do nothing and return
* true. This returned value is not used. * true. This returned value is not used.
@ -745,7 +760,7 @@ class PDOEngine extends PDO {
} }
/** /**
* Function to determine which query type the argument is. * Method to determine which query type the argument is.
* *
* It takes the query string ,determines the type and returns the type string. * It takes the query string ,determines the type and returns the type string.
* If the query is the type that SQLite Integration can't executes, returns false. * If the query is the type that SQLite Integration can't executes, returns false.
@ -754,7 +769,7 @@ class PDOEngine extends PDO {
* @return boolean|string * @return boolean|string
*/ */
private function determine_query_type($query) { private function determine_query_type($query) {
$result = preg_match('/^\\s*(EXPLAIN|PRAGMA|SELECT\\s*FOUND_ROWS|SELECT|INSERT|UPDATE|REPLACE|DELETE|ALTER|CREATE|DROP\\s*INDEX|DROP|SHOW\\s*\\w+\\s*\\w+\\s*|DESCRIBE|DESC|TRUNCATE|OPTIMIZE|CHECK|ANALYZE)/i', $query, $match); $result = preg_match('/^\\s*(SET|EXPLAIN|PRAGMA|SELECT\\s*FOUND_ROWS|SELECT|INSERT|UPDATE|REPLACE|DELETE|ALTER|CREATE|DROP\\s*INDEX|DROP|SHOW\\s*\\w+\\s*\\w+\\s*|DESCRIBE|DESC|TRUNCATE|OPTIMIZE|CHECK|ANALYZE)/i', $query, $match);
if (!$result) { if (!$result) {
return false; return false;
@ -764,7 +779,9 @@ class PDOEngine extends PDO {
$this->query_type = 'foundrows'; $this->query_type = 'foundrows';
} }
if (stripos($this->query_type, 'show') !== false) { if (stripos($this->query_type, 'show') !== false) {
if (stripos($this->query_type, 'show tables') !== false) { if (stripos($this->query_type, 'show table status') !== false) {
$this->query_type = 'showstatus';
} elseif (stripos($this->query_type, 'show tables') !== false) {
$this->query_type = 'show'; $this->query_type = 'show';
} elseif (stripos($this->query_type, 'show columns') !== false || stripos($this->query_type, 'show fields') !== false) { } elseif (stripos($this->query_type, 'show columns') !== false || stripos($this->query_type, 'show fields') !== false) {
$this->query_type = 'showcolumns'; $this->query_type = 'showcolumns';
@ -783,7 +800,7 @@ class PDOEngine extends PDO {
} }
/** /**
* Function to execute INSERT query for SQLite version 3.7.11 or later. * Method to execute INSERT query for SQLite version 3.7.11 or later.
* *
* SQLite version 3.7.11 began to support multiple rows insert with values * SQLite version 3.7.11 began to support multiple rows insert with values
* clause. This is for that version or later. * clause. This is for that version or later.
@ -799,7 +816,7 @@ class PDOEngine extends PDO {
$this->execute_query($statement); $this->execute_query($statement);
} }
/** /**
* Function to execute INSERT query for SQLite version 3.7.10 or lesser. * Method to execute INSERT query for SQLite version 3.7.10 or lesser.
* *
* It executes the INSERT query for SQLite version 3.7.10 or lesser. It is * It executes the INSERT query for SQLite version 3.7.10 or lesser. It is
* necessary to rewrite multiple row values. * necessary to rewrite multiple row values.
@ -857,7 +874,7 @@ class PDOEngine extends PDO {
} }
/** /**
* Function to help rewriting multiple row values insert query. * Method to help rewriting multiple row values insert query.
* *
* It splits the values clause into an array to execute separately. * It splits the values clause into an array to execute separately.
* *
@ -899,7 +916,7 @@ class PDOEngine extends PDO {
} }
/** /**
* Function to execute CREATE query. * Method to execute CREATE query.
* *
* @param string * @param string
* @return boolean * @return boolean
@ -936,7 +953,7 @@ class PDOEngine extends PDO {
return true; return true;
} }
/** /**
* Function to execute ALTER TABLE query. * Method to execute ALTER TABLE query.
* *
* @param string * @param string
* @return boolean * @return boolean
@ -988,7 +1005,7 @@ class PDOEngine extends PDO {
} }
/** /**
* Function to execute SHOW VARIABLES query * Method to execute SHOW VARIABLES query
* *
* This query is meaningless for SQLite. This function returns null data with some * This query is meaningless for SQLite. This function returns null data with some
* exceptions and only avoids the error message. * exceptions and only avoids the error message.
@ -1016,7 +1033,36 @@ class PDOEngine extends PDO {
return true; return true;
} }
/** /**
* Function to format the queried data to that of MySQL. * Method to execute SHOW TABLE STATUS query.
*
* This query is meaningless for SQLite. This function return dummy data.
*
* @param string
* @return ObjectArray
*/
private function show_status_workaround($query) {
$pattern = '/^SHOW\\s*TABLE\\s*STATUS\\s*LIKE\\s*(.*?)$/im';
if (preg_match($pattern, $query, $match)) {
$table_name = str_replace("'", '', $match[1]);
} else {
$table_name = '';
}
$dummy_data = array(
'Name' => $table_name, 'Engine' => '', 'Version' => '',
'Row_format' => '', 'Rows' => 0, 'Avg_row_length' => 0,
'Data_length' => 0, 'Max_data_length' => 0, 'Index_length' => 0,
'Data_free' => 0, 'Auto_increment' => 0, 'Create_time' => '',
'Update_time' => '', 'Check_time' => '', 'Collation' => '',
'Checksum' => '', 'Create_options' => '', 'Comment' => ''
);
$_results[] = new ObjectArray($dummy_data);
$this->results = $_results;
$this->num_rows = count($this->results);
$this->return_value = $this->num_rows;
return true;
}
/**
* Method to format the queried data to that of MySQL.
* *
* @param string $engine * @param string $engine
*/ */
@ -1032,7 +1078,7 @@ class PDOEngine extends PDO {
} }
} }
/** /**
* Function to format the error messages and put out to the file. * Method to format the error messages and put out to the file.
* *
* When $wpdb::suppress_errors is set to true or $wpdb::show_errors is set to false, * When $wpdb::suppress_errors is set to true or $wpdb::show_errors is set to false,
* the error messages are ignored. * the error messages are ignored.
@ -1052,7 +1098,7 @@ class PDOEngine extends PDO {
file_put_contents (FQDBDIR .'debug.txt', "Line $line, Function: $function, Message: $message \n", FILE_APPEND); file_put_contents (FQDBDIR .'debug.txt', "Line $line, Function: $function, Message: $message \n", FILE_APPEND);
} }
/** /**
* Function to change the queried data to PHP object format. * Method to change the queried data to PHP object format.
* *
* It takes the associative array of query results and creates a numeric * It takes the associative array of query results and creates a numeric
* array of anonymous objects * array of anonymous objects
@ -1071,7 +1117,7 @@ class PDOEngine extends PDO {
$this->results = $_results; $this->results = $_results;
} }
/** /**
* Function to convert the SHOW COLUMNS query data to an object. * Method to convert the SHOW COLUMNS query data to an object.
* *
* It rewrites pragma results to mysql compatible array * It rewrites pragma results to mysql compatible array
* when query_type is describe, we use sqlite pragma function. * when query_type is describe, we use sqlite pragma function.
@ -1103,7 +1149,7 @@ class PDOEngine extends PDO {
$this->results = $_results; $this->results = $_results;
} }
/** /**
* Function to convert SHOW INDEX query data to PHP object. * Method to convert SHOW INDEX query data to PHP object.
* *
* It rewrites the result of SHOW INDEX to the Object compatible with MySQL * It rewrites the result of SHOW INDEX to the Object compatible with MySQL
* added the WHERE clause manipulation (ver 1.3.1) * added the WHERE clause manipulation (ver 1.3.1)
@ -1193,7 +1239,7 @@ class PDOEngine extends PDO {
$this->results = $_results; $this->results = $_results;
} }
/** /**
* Function to the CHECK query data to an object. * Method to the CHECK query data to an object.
* *
* @access private * @access private
*/ */
@ -1218,7 +1264,7 @@ class PDOEngine extends PDO {
$this->results = $_results; $this->results = $_results;
} }
/** /**
* Function to check SQLite library version. * Method to check SQLite library version.
* *
* This is used for checking if SQLite can execute multiple rows insert. * This is used for checking if SQLite can execute multiple rows insert.
* *
@ -1236,7 +1282,7 @@ class PDOEngine extends PDO {
} }
} }
/** /**
* Function to call PDO::beginTransaction(). * Method to call PDO::beginTransaction().
* *
* @see PDO::beginTransaction() * @see PDO::beginTransaction()
* @return boolean * @return boolean
@ -1250,7 +1296,7 @@ class PDOEngine extends PDO {
} }
} }
/** /**
* Function to call PDO::commit(). * Method to call PDO::commit().
* *
* @see PDO::commit() * @see PDO::commit()
*/ */
@ -1259,7 +1305,7 @@ class PDOEngine extends PDO {
$this->has_active_transaction = false; $this->has_active_transaction = false;
} }
/** /**
* Function to call PDO::rollBack(). * Method to call PDO::rollBack().
* *
* @see PDO::rollBack() * @see PDO::rollBack()
*/ */

View File

@ -24,7 +24,30 @@ class PDOSQLiteDriver {
* @var string * @var string
*/ */
public $_query = ''; public $_query = '';
/**
* Variable to check if rewriting CALC_FOUND_ROWS is needed.
*
* @var boolean
*/
private $rewrite_calc_found = false;
/**
* Variable to check if rewriting ON DUPLICATE KEY UPDATE is needed.
*
* @var boolean
*/
private $rewrite_duplicate_key = false;
/**
* Variable to check if rewriting index hints is needed.
*
* @var boolean
*/
private $rewrite_index_hint = false;
/**
* Variable to check if rewriting BETWEEN is needed.
*
* @var boolean
*/
private $rewrite_between = false;
/** /**
* Method to rewrite a query string for SQLite to execute. * Method to rewrite a query string for SQLite to execute.
* *
@ -35,6 +58,7 @@ class PDOSQLiteDriver {
public function rewrite_query($query, $query_type){ public function rewrite_query($query, $query_type){
$this->query_type = $query_type; $this->query_type = $query_type;
$this->_query = $query; $this->_query = $query;
$this->parse_query();
switch ($this->query_type) { switch ($this->query_type) {
case 'truncate': case 'truncate':
$this->handle_truncate_query(); $this->handle_truncate_query();
@ -59,24 +83,24 @@ class PDOSQLiteDriver {
$this->handle_show_index(); $this->handle_show_index();
break; break;
case 'select': case 'select':
$this->strip_backticks(); //$this->strip_backticks();
$this->handle_sql_count(); $this->handle_sql_count();
$this->rewrite_date_sub(); $this->rewrite_date_sub();
$this->delete_index_hints(); $this->delete_index_hints();
$this->rewrite_regexp(); $this->rewrite_regexp();
$this->rewrite_boolean(); //$this->rewrite_boolean();
$this->fix_date_quoting(); $this->fix_date_quoting();
$this->rewrite_between(); $this->rewrite_between();
break; break;
case 'insert': case 'insert':
$this->safe_strip_backticks(); //$this->safe_strip_backticks();
$this->execute_duplicate_key_update(); $this->execute_duplicate_key_update();
$this->rewrite_insert_ignore(); $this->rewrite_insert_ignore();
$this->rewrite_regexp(); $this->rewrite_regexp();
$this->fix_date_quoting(); $this->fix_date_quoting();
break; break;
case 'update': case 'update':
$this->safe_strip_backticks(); //$this->safe_strip_backticks();
$this->rewrite_update_ignore(); $this->rewrite_update_ignore();
// $this->_rewrite_date_sub(); // $this->_rewrite_date_sub();
$this->rewrite_limit_usage(); $this->rewrite_limit_usage();
@ -85,7 +109,7 @@ class PDOSQLiteDriver {
$this->rewrite_between(); $this->rewrite_between();
break; break;
case 'delete': case 'delete':
$this->strip_backticks(); //$this->strip_backticks();
$this->rewrite_limit_usage(); $this->rewrite_limit_usage();
$this->rewrite_order_by_usage(); $this->rewrite_order_by_usage();
$this->rewrite_date_sub(); $this->rewrite_date_sub();
@ -93,7 +117,7 @@ class PDOSQLiteDriver {
$this->delete_workaround(); $this->delete_workaround();
break; break;
case 'replace': case 'replace':
$this->safe_strip_backticks(); //$this->safe_strip_backticks();
$this->rewrite_date_sub(); $this->rewrite_date_sub();
$this->rewrite_regexp(); $this->rewrite_regexp();
break; break;
@ -113,6 +137,60 @@ class PDOSQLiteDriver {
return $this->_query; return $this->_query;
} }
/**
* Method to parse query string and determine which operation is needed.
*
* Remove backticks and change true/false values into 1/0. And determines
* if rewriting CALC_FOUND_ROWS or ON DUPLICATE KEY UPDATE etc is needed.
*
* @access private
*/
private function parse_query() {
$tokens = preg_split("/(''|')/s", $this->_query, -1, PREG_SPLIT_DELIM_CAPTURE);
$literal = false;
$query_string = '';
foreach ($tokens as $token) {
if ($token == "'") {
if ($literal) {
$literal = false;
} else {
$literal = true;
}
} else {
if ($literal === false) {
if (strpos($token, '`') !== false) {
$token = str_replace('`', '', $token);
}
if (stripos($token, 'TRUE') !== false) {
$token = str_ireplace('TRUE', '1', $token);
}
if (stripos($token, 'FALSE') !== false) {
$token = str_ireplace('FALSE', '0', $token);
}
if (stripos($token, 'SQL_CALC_FOUND_ROWS') !== false) {
$this->rewrite_calc_found = true;
}
if (stripos($token, 'ON DUPLICATE KEY UPDATE') !== false) {
$this->rewrite_duplicate_key = true;
}
if (stripos($token, 'USE INDEX') !== false) {
$this->rewrite_index_hint = true;
}
if (stripos($token, 'IGNORE INDEX') !== false) {
$this->rewrite_index_hint = true;
}
if (stripos($token, 'FORCE INDEX') !== false) {
$this->rewrite_index_hint = true;
}
if (stripos($token, 'BETWEEN') !== false) {
$this->rewrite_between = true;
}
}
}
$query_string .= $token;
}
$this->_query = $query_string;
}
/** /**
* method to handle SHOW TABLES query. * method to handle SHOW TABLES query.
* *
@ -137,6 +215,8 @@ class PDOSQLiteDriver {
* All the back quotes in the query string are removed automatically. * All the back quotes in the query string are removed automatically.
* So it must not be used when INSERT, UPDATE or REPLACE query is executed. * So it must not be used when INSERT, UPDATE or REPLACE query is executed.
* *
* Obsolite since 1.5.1
*
* @access private * @access private
*/ */
private function strip_backticks(){ private function strip_backticks(){
@ -148,6 +228,8 @@ class PDOSQLiteDriver {
* All the back quotes execpt user data to be inserted are revomved automatically. * All the back quotes execpt user data to be inserted are revomved automatically.
* This method must be used when INSERT, UPDATE or REPLACE query is executed. * This method must be used when INSERT, UPDATE or REPLACE query is executed.
* *
* Obsolite since 1.5.1
*
* @access private * @access private
*/ */
private function safe_strip_backticks() { private function safe_strip_backticks() {
@ -187,20 +269,19 @@ class PDOSQLiteDriver {
* @access private * @access private
*/ */
private function handle_sql_count(){ private function handle_sql_count(){
if (stripos($this->_query, 'SELECT SQL_CALC_FOUND_ROWS') !== false){ if (!$this->rewrite_calc_found) return;
global $wpdb; global $wpdb;
// first strip the code. this is the end of rewriting process // first strip the code. this is the end of rewriting process
$this->_query = str_ireplace('SQL_CALC_FOUND_ROWS', '', $this->_query); $this->_query = str_ireplace('SQL_CALC_FOUND_ROWS', '', $this->_query);
// we make the data for next SELECE FOUND_ROWS() statement // we make the data for next SELECE FOUND_ROWS() statement
$unlimited_query = preg_replace('/\\bLIMIT\\s*.*/imsx', '', $this->_query); $unlimited_query = preg_replace('/\\bLIMIT\\s*.*/imsx', '', $this->_query);
$unlimited_query = preg_replace('/\\bGROUP\\s*BY\\s*.*/imsx', '', $unlimited_query); //$unlimited_query = preg_replace('/\\bGROUP\\s*BY\\s*.*/imsx', '', $unlimited_query);
// we no longer use SELECT COUNT query // we no longer use SELECT COUNT query
// $unlimited_query = $this->_transform_to_count($unlimited_query); //$unlimited_query = $this->_transform_to_count($unlimited_query);
$_wpdb = new PDODB(); $_wpdb = new PDODB();
$result = $_wpdb->query($unlimited_query); $result = $_wpdb->query($unlimited_query);
$wpdb->dbh->found_rows_result = $result; $wpdb->dbh->found_rows_result = $result;
$_wpdb = null; $_wpdb = null;
}
} }
/** /**
* Call back method to change SELECT query to SELECT COUNT(). * Call back method to change SELECT query to SELECT COUNT().
@ -442,6 +523,8 @@ class PDOSQLiteDriver {
* *
* SQLite doesn't support true/false type, so we need to convert them to 1/0. * SQLite doesn't support true/false type, so we need to convert them to 1/0.
* *
* Obsolite since 1.5.1
*
* @access private * @access private
*/ */
private function rewrite_boolean() { private function rewrite_boolean() {
@ -495,31 +578,11 @@ class PDOSQLiteDriver {
* @access private * @access private
*/ */
private function execute_duplicate_key_update() { private function execute_duplicate_key_update() {
$rewrite_flag = true; if (!$this->rewrite_duplicate_key) return;
$update = false;
$unique_keys_for_cond = array(); $unique_keys_for_cond = array();
$unique_keys_for_check = array(); $unique_keys_for_check = array();
$pattern = '/^\\s*INSERT\\s*INTO\\s*(\\w+)?\\s*(.*)\\s*ON\\s*DUPLICATE\\s*KEY\\s*UPDATE\\s*(.*)$/ims'; $pattern = '/^\\s*INSERT\\s*INTO\\s*(\\w+)?\\s*(.*)\\s*ON\\s*DUPLICATE\\s*KEY\\s*UPDATE\\s*(.*)$/ims';
if (preg_match($pattern, $this->_query, $match_0)) { if (preg_match($pattern, $this->_query, $match_0)) {
$tokens = preg_split("/(''|')/s", $this->_query, -1, PREG_SPLIT_DELIM_CAPTURE);
$literal = false;
foreach ($tokens as $token) {
if (strpos($token, "'") !== false) {
if ($literal) {
$literal = false;
} else {
$literal = true;
}
} else {
if ($literal === false && stripos($token, 'ON DUPLICATE KEY UPDATE') !== false) {
$rewrite_flag = true;
break;
} else {
$rewrite_flag = false;
}
}
}
if (!$rewrite_flag) return;
$table_name = trim($match_0[1]); $table_name = trim($match_0[1]);
$insert_data = trim($match_0[2]); $insert_data = trim($match_0[2]);
$update_data = trim($match_0[3]); $update_data = trim($match_0[3]);
@ -654,33 +717,15 @@ class PDOSQLiteDriver {
* @access private * @access private
*/ */
private function rewrite_between() { private function rewrite_between() {
if (!$this->rewrite_between) return;
$pattern = '/\\s*(\\w+)?\\s*BETWEEN\\s*([^\\s]*)?\\s*AND\\s*([^\\s]*)?\\s*/ims'; $pattern = '/\\s*(\\w+)?\\s*BETWEEN\\s*([^\\s]*)?\\s*AND\\s*([^\\s]*)?\\s*/ims';
if (preg_match($pattern, $this->_query, $match)) { if (preg_match($pattern, $this->_query, $match)) {
$column_name = trim($match[1]); $column_name = trim($match[1]);
$min_value = trim($match[2]); $min_value = trim($match[2]);
$max_value = trim($match[3]); $max_value = trim($match[3]);
$max_value = rtrim($max_value); $max_value = rtrim($max_value);
$tokens = preg_split("/(''|')/s", $this->_query, -1, PREG_SPLIT_DELIM_CAPTURE); $replacement = " $column_name >= '$min_value' AND $column_name <= '$max_value'";
$literal = false; $this->_query = str_ireplace($match[0], $replacement, $this->_query);
$rewriting = false;
foreach ($tokens as $token) {
if ($token == "'") {
if ($literal) {
$literal = false;
} else {
$literal = true;
}
} else {
if ($literal === false && stripos($token, 'between') !== false) {
$rewriting = true;
break;
}
}
}
if ($rewriting) {
$replacement = " $column_name >= '$min_value' AND $column_name <= '$max_value'";
$this->_query = str_ireplace($match[0], $replacement, $this->_query);
}
} }
} }
/** /**

View File

@ -78,6 +78,7 @@ class CreateQuery{
$this->rewrite_unsigned(); $this->rewrite_unsigned();
$this->rewrite_autoincrement(); $this->rewrite_autoincrement();
$this->rewrite_primary_key(); $this->rewrite_primary_key();
$this->rewrite_foreign_key();
$this->rewrite_unique_key(); $this->rewrite_unique_key();
$this->rewrite_enum(); $this->rewrite_enum();
$this->rewrite_set(); $this->rewrite_set();
@ -190,19 +191,32 @@ class CreateQuery{
*/ */
private function rewrite_primary_key(){ private function rewrite_primary_key(){
if ($this->has_primary_key) { if ($this->has_primary_key) {
$this->_query = preg_replace('/\\bprimary key\\s*\([^\)]*\)/ims', ' ', $this->_query); $this->_query = preg_replace('/\\s*primary key\\s*.*?\([^\)]*\)\\s*(,|)/i', ' ', $this->_query);
} else { } else {
// If primary key has an index name, we remove that name. // If primary key has an index name, we remove that name.
$this->_query = preg_replace('/\\bprimary\\s*key\\s*.*?\\s*(\(.*?\))/im', 'PRIMARY KEY \\1', $this->_query); $this->_query = preg_replace('/\\bprimary\\s*key\\s*.*?\\s*(\(.*?\))/im', 'PRIMARY KEY \\1', $this->_query);
} }
} }
/**
* Method for rewriting foreign key.
*
* @access private
*/
private function rewrite_foreign_key() {
$pattern = '/\\s*foreign\\s*key\\s*(|.*?)\([^\)]+?\)\\s*references\\s*.*/i';
if (preg_match_all($pattern, $this->_query, $match)) {
if (isset($match[1])) {
$this->_query = str_ireplace($match[1], '', $this->_query);
}
}
}
/** /**
* Method for rewriting unique key. * Method for rewriting unique key.
* *
* @access private * @access private
*/ */
private function rewrite_unique_key(){ private function rewrite_unique_key(){
$this->_query = preg_replace_callback('/\\bunique key\\b([^\(]*)(\([^\)]*\))/ims', array($this, '_rewrite_unique_key'), $this->_query); $this->_query = preg_replace_callback('/\\bunique key\\b([^\(]*)(\(.*\))/im', array($this, '_rewrite_unique_key'), $this->_query);
} }
/** /**
* Callback method for rewrite_unique_key. * Callback method for rewrite_unique_key.
@ -214,6 +228,9 @@ class CreateQuery{
$index_name = trim($matches[1]); $index_name = trim($matches[1]);
$col_name = trim($matches[2]); $col_name = trim($matches[2]);
$tbl_name = $this->table_name; $tbl_name = $this->table_name;
if (preg_match('/\(\\d+?\)/', $col_name)) {
$col_name = preg_replace('/\(\\d+?\)/', '', $col_name);
}
$_wpdb = new PDODB(); $_wpdb = new PDODB();
$results = $_wpdb->get_results("SELECT name FROM sqlite_master WHERE type='index'"); $results = $_wpdb->get_results("SELECT name FROM sqlite_master WHERE type='index'");
$_wpdb = null; $_wpdb = null;

View File

@ -6,8 +6,8 @@ Tags: database, SQLite, PDO
Author: Kojima Toshiyasu Author: Kojima Toshiyasu
Author URI: http://dogwood.skr.jp/ Author URI: http://dogwood.skr.jp/
Requires at least: 3.3 Requires at least: 3.3
Tested up to: 3.8.1 Tested up to: 3.9
Stable tag: 1.5 Stable tag: 1.6
License: GPLv2 License: GPLv2
License URI: http://www.gnu.org/licenses/gpl-2.0.html License URI: http://www.gnu.org/licenses/gpl-2.0.html
@ -151,7 +151,9 @@ SQLite に戻りたいときには、この行を次のように変更するか
たぶん、もっとあるでしょう。動作しないプラグインを見つけたら、お知らせいただけると助かります。 たぶん、もっとあるでしょう。動作しないプラグインを見つけたら、お知らせいただけると助かります。
非互換のプラグインの中には、少し修正をすると、使えるようになるものがあります。[Plugins(ja)](http://dogwood.skr.jp/wordpress/plugins-ja/)で情報を公開しいますので、参照してください。 非互換のプラグインの中には、少し修正をすると、使えるようになるものがあります。[Plugins(ja)](http://dogwood.skr.jp/wordpress/plugins-ja/)で情報を公開していますので、参照してください。
このプラグインは、'WP_PLUGIN_URL' 定数をサポートしません。
== Upgrade Notice == == Upgrade Notice ==
@ -159,7 +161,7 @@ query_posts() や WP_Query() を使うときに、オプションの一部が機
== Changelog == == Changelog ==
= 1.5.1 (2014-02-06) = = 1.6 (2014-04-27) =
* 未対応のクエリに対するエラーメッセージのコントロールができていないのを修正しました。 * 未対応のクエリに対するエラーメッセージのコントロールができていないのを修正しました。
* SQL_CALC_FOUND_ROW ステートメントのバグを修正しました。メインクエリと WP_Query、WP_Meta_Query などのページング情報に関連したものです。 * SQL_CALC_FOUND_ROW ステートメントのバグを修正しました。メインクエリと WP_Query、WP_Meta_Query などのページング情報に関連したものです。
* コメント本文からバッククォートが削除されるバグを修正しました。 * コメント本文からバッククォートが削除されるバグを修正しました。
@ -167,7 +169,7 @@ query_posts() や WP_Query() を使うときに、オプションの一部が機
* PHP documentor で使えるように、ソースコードのドキュメントを書き直しました。 * PHP documentor で使えるように、ソースコードのドキュメントを書き直しました。
* このドキュメントを変えました。 * このドキュメントを変えました。
* マイナーな変更、修正がいくつかありました。 * マイナーな変更、修正がいくつかありました。
* WordPress 3.8.1 と 3.9 alpha でインストールテストをしました。 * WordPress 3.8.2 と 3.9 alpha でインストールテストをしました。
* プラグイン互換リストを増補しました。 * プラグイン互換リストを増補しました。
* これまで使えなくしていた wp-db.php の関数を使えるようにしました。 * これまで使えなくしていた wp-db.php の関数を使えるようにしました。
* いくつかのユーザ定義関数を追加しました。 * いくつかのユーザ定義関数を追加しました。

View File

@ -6,8 +6,8 @@ Tags: database, SQLite, PDO
Author: Kojima Toshiyasu Author: Kojima Toshiyasu
Author URI: http://dogwood.skr.jp/ Author URI: http://dogwood.skr.jp/
Requires at least: 3.3 Requires at least: 3.3
Tested up to: 3.8.1 Tested up to: 3.9
Stable tag: 1.5 Stable tag: 1.6
License: GPLv2 License: GPLv2
License URI: http://www.gnu.org/licenses/gpl-2.0.html License URI: http://www.gnu.org/licenses/gpl-2.0.html
@ -151,13 +151,15 @@ You may be able to use 'WordPress Related Posts' or 'Related Posts' instead of t
There are some among the incompatible plugins, which work fine by rewriting some codes. I give information about them and provide the patch files on [Plugins](http://dogwood.skr.jp/wordpress/plugins/). There are some among the incompatible plugins, which work fine by rewriting some codes. I give information about them and provide the patch files on [Plugins](http://dogwood.skr.jp/wordpress/plugins/).
This plugin doesn't support 'WP_PLUGIN_URL' constant.
== Upgrade Notice == == Upgrade Notice ==
When query_posts() or WP_Query() is used, some options didn't work properly. When you post comments, the back quotes in the content was removed. These bugs and some minor ones are fixed. Documentations and doc strings are revised. WordPress 3.9 beta was tested. When auto upgrading fails, please try manual upgrade via FTP. When query_posts() or WP_Query() is used, some options didn't work properly. When you post comments, the back quotes in the content was removed. These bugs and some minor ones are fixed. Documentations and doc strings are revised. WordPress 3.9 beta was tested. When auto upgrading fails, please try manual upgrade via FTP.
== Changelog == == Changelog ==
= 1.5.1 (2014-02-06) = = 1.6 (2014-04-10) =
* Fixed the bug of error messaging control for the unknown query. * Fixed the bug of error messaging control for the unknown query.
* Fixed the bug for 'SQL_CALC_FOUND_ROW' statement. This is for the main query, WP_Query class and WP_Meta_Query concerning paging information. * Fixed the bug for 'SQL_CALC_FOUND_ROW' statement. This is for the main query, WP_Query class and WP_Meta_Query concerning paging information.
* Fixed the bug that the back quote in the comments was removed. * Fixed the bug that the back quote in the comments was removed.
@ -165,7 +167,7 @@ When query_posts() or WP_Query() is used, some options didn't work properly. Whe
* Revised all the doc strings in the sourcse code for PHP documentor. * Revised all the doc strings in the sourcse code for PHP documentor.
* Changed the documentation. * Changed the documentation.
* Fixed minor bugs and typos. * Fixed minor bugs and typos.
* Tested to install WordPress 3.8.1 and 3.9 beta. * Tested to install WordPress 3.8.2 and 3.9 beta.
* Augumented the plugin compatibility list. * Augumented the plugin compatibility list.
* Some functions in wp-db.php, which was disabled by the plugin, is enabled and can be used. * Some functions in wp-db.php, which was disabled by the plugin, is enabled and can be used.
* Some more user defined functions are added. * Some more user defined functions are added.

View File

@ -32,8 +32,7 @@ function make_db_sqlite() {
$err_data = $err->errorInfo; $err_data = $err->errorInfo;
$message = 'Database connection error!<br />'; $message = 'Database connection error!<br />';
$message .= sprintf("Error message is: %s", $err_data[2]); $message .= sprintf("Error message is: %s", $err_data[2]);
echo $message; wp_die($message, 'Database Error!');
return false;
} }
try { try {
@ -86,8 +85,7 @@ function make_db_sqlite() {
$pdo->rollBack(); $pdo->rollBack();
$message = sprintf("Error occured while creating tables or indexes...<br />Query was: %s<br />", var_export($rewritten_query, true)); $message = sprintf("Error occured while creating tables or indexes...<br />Query was: %s<br />", var_export($rewritten_query, true));
$message .= sprintf("Error message is: %s", $err_data[2]); $message .= sprintf("Error message is: %s", $err_data[2]);
echo $message; wp_die($message, 'Database Error!');
return false;
} }
} }

View File

@ -4,7 +4,7 @@ Plugin Name: SQLite Integration
Plugin URI: http://dogwood.skr.jp/wordpress/sqlite-integration/ Plugin URI: http://dogwood.skr.jp/wordpress/sqlite-integration/
Description: SQLite Integration is the plugin that enables WordPress to use SQLite. If you don't have MySQL and want to build a WordPress website, it's for you. Description: SQLite Integration is the plugin that enables WordPress to use SQLite. If you don't have MySQL and want to build a WordPress website, it's for you.
Author: Kojima Toshiyasu Author: Kojima Toshiyasu
Version: 1.5 Version: 1.6
Author URI: http://dogwood.skr.jp Author URI: http://dogwood.skr.jp
Text Domain: sqlite-integration Text Domain: sqlite-integration
Domain Path: /languages Domain Path: /languages
@ -47,7 +47,11 @@ $siteurl = get_option('siteurl');
define('SQLiteDir', dirname(plugin_basename(__FILE__))); define('SQLiteDir', dirname(plugin_basename(__FILE__)));
define('SQLiteFilePath', dirname(__FILE__)); define('SQLiteFilePath', dirname(__FILE__));
define('SQLiteDirName', basename(SQLiteFilePath)); define('SQLiteDirName', basename(SQLiteFilePath));
define('SQLiteUrl', $siteurl . '/wp-content/plugins/' . SQLiteDir); if (defined('WP_PLUGIN_URL')) {
define('SQLiteUrl', WP_PLUGIN_URL . '/' . SQLiteDir);
} else {
define('SQLiteUrl', $siteurl . '/wp-content/plugins/' . SQLiteDir);
}
/* /*
* Defines patch file upload directory. * Defines patch file upload directory.
*/ */

View File

@ -400,7 +400,7 @@ class SQLiteIntegrationUtils {
*/ */
private function get_backup_files() { private function get_backup_files() {
$db_name = basename(FQDB); $db_name = basename(FQDB);
$names_to_exclude = array('.', '..', '.htaccess', 'debug.txt', '.ht.sqlite', $db_name); $names_to_exclude = array('.', '..', '.htaccess', 'debug.txt', '.ht.sqlite', 'index.php', $db_name);
$backup_files = array(); $backup_files = array();
if (is_dir(FQDBDIR)) { if (is_dir(FQDBDIR)) {
if ($dir_handle = opendir(FQDBDIR)) { if ($dir_handle = opendir(FQDBDIR)) {
@ -952,21 +952,22 @@ class SQLiteIntegrationUtils {
</p> </p>
</form> </form>
<h3><?php _e('Edit Initial File (wp-content/db.php)', $domain)?></h3> <?php if (!(defined('DISALLOW_FILE_EDIT') && DISALLOW_FILE_EDIT) || !(defined('DISALLOW_FILE_DODS') && DISALLOW_FILE_MODS)) : ?>
<p> <?php echo '<h3>';?>
<?php _e('When you go &quot;Plugins &raquo; Edit Plugin&quot; page, you can edit plugin source file. But you can\'t see this file there because it is not in the plugin directory. If you need to edit this file, you can edit here. This settings may cause problems. <span class="alert">If you don\'t understand well, please don\'t edit this file</span>.', $domain)?> <?php _e('Edit Initial File (wp-content/db.php)', $domain)?>
</p> <?php echo '</h3><p>'; ?>
<form action="" method="post"> <?php _e('When you go &quot;Plugins &raquo; Edit Plugin&quot; page, you can edit plugin source file. But you can\'t see this file there because it is not in the plugin directory. If you need to edit this file, you can edit here. This settings may cause problems. <span class="alert">If you don\'t understand well, please don\'t edit this file</span>.', $domain)?>
<?php echo '</p>'; ?>
<?php echo '<form action="" method="post">'; ?>
<?php if (function_exists('wp_nonce_field')) { <?php if (function_exists('wp_nonce_field')) {
wp_nonce_field('sqlitewordpress-db-save-stats'); wp_nonce_field('sqlitewordpress-db-save-stats');
} }?>
?> <?php echo '<textarea name="dbfile" id="dbfile" cols="70" rows="10">'; ?>
<textarea name="dbfile" id="dbfile" cols="70" rows="10"> <?php $this->show_db_php();?>
<?php $this->show_db_php();?></textarea> <?php echo '</textarea><p>'; ?>
<p> <?php sprintf('<input type="submit" name="sqlitewordpress_db_save" value="%s" onclick="return confirm(\'%s\')" class="button-primary">', __('Save', $domain), __('Are you sure to save this file?\n\nClick [Cancel] to stop, [OK] to continue.', $domain)); ?>
<input type="submit" name="sqlitewordpress_db_save" value="<?php _e('Save')?>" onclick="return confirm('<?php _e('Are you sure to save this file?\n\nClick [Cancel] to stop, [OK] to continue.', $domain);?>')" class="button-primary"> <?php echo '</p></form>'; ?>
</p> <?php endif;?>
</form>
</div> </div>
<?php endif; <?php endif;