• R/O
  • HTTP
  • SSH
  • HTTPS

nucleus-plugins: Commit

Nucleus CMS日本語版用プラグインのうち、日本語版開発者がサポートしているもの


Commit MetaInfo

Revision6047bcc6ccfae982c723a61a7d645d7ef62a000b (tree)
Time2008-02-05 12:36:01
Authorkmorimatsu <kmorimatsu@1ca2...>
Commiterkmorimatsu

Log Message

// Version 0.8.6.0
// - ALTER TABLE almost completery re-written
// - DESC 'table' 'field' supported
// - The function 'php' is unregestered from SQL query.

git-svn-id: https://svn.sourceforge.jp/svnroot/nucleus-jp/plugin@603 1ca29b6e-896d-4ea0-84a5-967f57386b96

Change Summary

Incremental Difference

--- a/trunk/sqlite/nucleus/sqlite/sqlite.php
+++ b/trunk/sqlite/nucleus/sqlite/sqlite.php
@@ -1,9 +1,9 @@
11 <?php
2- /***************************************
3- * SQLite-MySQL wrapper for Nucleus *
4- * ver 0.8.5.6*
5- * Written by Katsumi *
6- ***************************************/
2+ /****************************************
3+ * SQLite-MySQL wrapper for Nucleus *
4+ * ver 0.8.6.0 *
5+ * Written by Katsumi *
6+ ****************************************/
77 //
88 // The licence of this script is GPL
99 //
@@ -47,16 +47,21 @@
4747 //
4848 // Version 0.8.5.5
4949 // - ALTER TABLE syntaxes updated, bugs fixed
50+//
51+// Version 0.8.6.0
52+// - ALTER TABLE almost completery re-written
53+// - DESC 'table' 'field' supported
54+// - The function 'php' is unregestered from SQL query.
5055
5156 // Check SQLite installed
5257
53-if (!function_exists('sqlite_open')) exit('Sorry, SQLite is not installed in the server.');
58+if (!function_exists('sqlite_open')) exit('Sorry, SQLite is not available from PHP (maybe, not installed in the server).');
5459
5560 // Initializiation stuff
5661 require_once dirname(__FILE__) . '/sqliteconfig.php';
5762 $SQLITE_DBHANDLE=sqlite_open($SQLITECONF['DBFILENAME']);
5863 require_once dirname(__FILE__) . '/sqlitequeryfunctions.php';
59-$SQLITECONF['VERSION']='0.8.5';
64+$SQLITECONF['VERSION']='0.8.5.8';
6065
6166 //Following thing may work if MySQL is NOT installed in server.
6267 if (!function_exists('mysql_query')) {
@@ -97,7 +102,7 @@ function sqlite_ReturnWithError($text='Not supported',$more=''){
97102 foreach($a as $key=>$btrace) {
98103 if (!($templine=$btrace['line'])) continue;
99104 if (!($tempfile=$btrace['file'])) continue;
100- $file=str_replace("\\",'/',$file);
105+ $file=str_replace('\\','/',$file);
101106 if (!$line && !$file && strpos($tempfile,'/sqlite.php')===false && strpos($tempfile,'/sqlitequeryfunctions.php')===false) {
102107 $line=$templine;
103108 $file=$tempfile;
@@ -127,6 +132,8 @@ function nucleus_mysql_connect($p1=null,$p2=null,$p3=null,$p4=null,$p5=null){
127132 if (!$SQLITE_DBHANDLE) $SQLITE_DBHANDLE=sqlite_open($SQLITECONF['DBFILENAME']);
128133 // Initialization queries.
129134 foreach($SQLITECONF['INITIALIZE'] as $value) nucleus_mysql_query($value);
135+ // Unregister the function 'php' in sql query.
136+ sqlite_create_function($SQLITE_DBHANDLE,'php','pi');
130137 return $SQLITE_DBHANDLE;
131138 }
132139
@@ -257,12 +264,13 @@ function sqlite_mysql_query_sub($dbhandle,$query,$strpositions=array(),$p1=null,
257264 if ($i=strpos($query,' ')) {
258265 $tablename=trim(substr($query,0,$i));
259266 $query=trim(substr($query,$i));
267+ require_once('sqlitealtertable.php');
260268 $ret =sqlite_altertable($tablename,$query,$dbhandle);
261269 if (!$ret) sqlite_ReturnWithError('SQL error',"<br /><i>".nucleus_mysql_error()."</i><br />".htmlspecialchars($p1)."<br /><br />\n".htmlspecialchars("ALTER TABLE $tablename $query")."<hr />\n");
262270 return $ret;
263271 }
264272 // Syntax error
265- $query=='DROP TABLE '.$query;
273+ //$query=='DROP TABLE '.$query;
266274 } else if (strpos($uquery,'INSERT INTO ')===0 || strpos($uquery,'REPLACE INTO ')===0 ||
267275 strpos($uquery,'INSERT IGNORE INTO ')===0 || strpos($uquery,'REPLACE IGNORE INTO ')===0) {
268276 $buff=str_replace(' IGNORE ',' OR IGNORE ',substr($uquery,0,($i=strpos($uquery,' INTO ')+6)));
@@ -318,6 +326,8 @@ function sqlite_mysql_query_sub($dbhandle,$query,$strpositions=array(),$p1=null,
318326 $query=sqlite_showFieldsFrom(trim(substr($query,18)),$dbhandle);
319327 } else if (strpos($uquery,'TRUNCATE TABLE ')===0) {
320328 $query='DELETE FROM '.substr($query,15);
329+ } else if (preg_match('/DESC\s+\'([^\']+)\'\s+\'([^\']+)\'\s*$/',$query,$m)) {
330+ return nucleus_mysql_query("SHOW FIELDS FROM '$m[1]' LIKE '$m[2]'");
321331 } else SQLite_Functions::sqlite_modifyQueryForUserFunc($query,$strpositions);
322332
323333 //Throw query again.
@@ -349,13 +359,15 @@ function sqlite_changeQuote(&$query){
349359 if (($i2=strpos($query,"'",$i))===false) $i2=$qlen;
350360 if (($i3=strpos($query,'`',$i))===false) $i3=$qlen;
351361 if ($i1==$qlen && $i2==$qlen && $i3==$qlen) {
352- $ret.=($temp=substr($query,$i));
362+ $temp=preg_replace('/[\s]+/',' ',substr($query,$i)); // Change all spacying to ' '.
363+ $ret.=($temp);
353364 if (strstr($temp,';')) exit('Warning: try to use more than two queries?');
354365 break;
355366 }
356367 if ($i2<($j=$i1)) $j=$i2;
357368 if ($i3<$j) $j=$i3;
358- $ret.=($temp=substr($query,$i,$j-$i));
369+ $temp=preg_replace('/[\s]+/',' ',substr($query,$i,$j-$i)); // Change all spacying to ' '.
370+ $ret.=($temp);
359371 $c=$query[($i=$j)]; // $c keeps the type of quote.
360372 if (strstr($temp,';')) exit('Warning: try to use more than two queries?');
361373
@@ -424,162 +436,6 @@ function sqlite_changeslashes(&$text){
424436 if ($text==='') return '';
425437 return (sqlite_escape_string (stripcslashes((string)$text)));
426438 }
427-function sqlite_altertable($table,$alterdefs,$dbhandle){
428- // This function originaly came from Jon Jensen's PHP class, SQLiteDB.
429- // There are some modifications by Katsumi.
430- $table=str_replace("'",'',$table);
431- if (!$alterdefs) return false;
432- $result = sqlite_query($dbhandle,"SELECT sql,name,type FROM sqlite_master WHERE tbl_name = '".$table."' ORDER BY type DESC");
433- if(!sqlite_num_rows($result)) return sqlite_ReturnWithError('no such table: '.$table);
434- $row = sqlite_fetch_array($result); //table sql
435- if (function_exists('microtime')) $tmpname='t'.str_replace('.','',str_replace(' ','',microtime()));
436- else $tmpname = 't'.rand(0,999999).time();
437- $origsql = trim(preg_replace("/[\s]+/"," ",str_replace(",",", ",preg_replace("/[\(]/","( ",$row['sql'],1))));
438- $createtemptableSQL = 'CREATE TEMPORARY '.substr(trim(preg_replace("'".$table."'",$tmpname,$origsql,1)),6);
439- $createindexsql = array();
440- while ($row = sqlite_fetch_array($result)) {//index sql
441- $createindexsql[]=$row['sql'];
442- }
443- $i = 0;
444- $defs = _sqlite_divideByChar(',',$alterdefs);
445- $prevword = $table;
446- $oldcols = _sqlite_divideByChar(',',substr(trim($createtemptableSQL),strpos(trim($createtemptableSQL),'(')+1));
447- $newcols = array();
448- for($i=0;$i<sizeof($oldcols);$i++){
449- $colparts = _sqlite_divideByChar(array(' ',"\t","\r","\n"),$oldcols[$i]);
450- $oldcols[$i] = $colparts[0];
451- $newcols[$colparts[0]] = $colparts[0];
452- }
453- $newcolumns = '';
454- $oldcolumns = '';
455- reset($newcols);
456- while(list($key,$val) = each($newcols)){
457- if (strtoupper($val)!='PRIMARY' && strtoupper($key)!='PRIMARY' &&
458- strtoupper($val)!='UNIQUE' && strtoupper($key)!='UNIQUE'){
459- $newcolumns .= ($newcolumns?', ':'').$val;
460- $oldcolumns .= ($oldcolumns?', ':'').$key;
461- }
462- }
463- $copytotempsql = 'INSERT INTO '.$tmpname.'('.$newcolumns.') SELECT '.$oldcolumns.' FROM '.$table;
464- $dropoldsql = 'DROP TABLE '.$table;
465- $createtesttableSQL = $createtemptableSQL;
466- foreach($defs as $def){
467- $defparts = _sqlite_divideByChar(array(' ',"\t","\r","\n"),$def);
468- $action = strtolower($defparts[0]);
469- switch($action){
470- case 'modify':
471- // Modification does not mean anything for SQLite, so just return true.
472- // But this command will be supported in future???
473- break;
474- case 'add':
475- if(($i=sizeof($defparts)) <= 2) return sqlite_ReturnWithError('near "'.$defparts[0].($defparts[1]?' '.$defparts[1]:'').'": syntax error');
476- // ignore if there is already such table
477- $exists=false;
478- foreach($oldcols as $value) if (str_replace("'",'',$defparts[1])==str_replace("'",'',$value)) $exists=true;
479- if ($exists) break;
480- // Support 'AFTER xxxx' statement.
481- // Support 'FIRST' statement.
482- $position=false;
483- if (4<=$i && strtoupper($defparts[$i-2])=='AFTER') {
484- $exists=false;
485- foreach($oldcols as $value) if (str_replace("'",'',$defparts[$i-2])==str_replace("'",'',$value)) $exists=$value;
486- if ($exists) {
487- if ( $position=strpos($createtesttableSQL,$exists) ){
488- if ( $position=strpos($createtesttableSQL,',',$position) ) $position++;// If ',' cannot be found (i.e. trying to put after the last column, $position will be false.
489- }
490- }
491- unset($defparts[$i-1],$defparts[$i-2]);
492- } else if (3<=$i && strtoupper($defparts[$i-1])=='FIRST') {
493- if ( $position=strpos($createtesttableSQL,'(') ) $position++;
494- unset($defparts[$i-1]);
495- }
496- // add new column here
497- if ($position) {// insert at the first position or between two columns
498- $afterpos = substr($createtesttableSQL,$position);
499- $createtesttableSQL = substr($createtesttableSQL,0,$position);
500- for($i=1;$i<sizeof($defparts);$i++) $createtesttableSQL.=' '.$defparts[$i];
501- $createtesttableSQL.=', '.$afterpos;
502- } else {// add at the last position
503- $createtesttableSQL = substr($createtesttableSQL,0,strlen($createtesttableSQL)-1).',';
504- for($i=1;$i<sizeof($defparts);$i++) $createtesttableSQL.=' '.$defparts[$i];
505- $createtesttableSQL.=')';
506- }
507- break;
508- case 'change':
509- if(sizeof($defparts) <= 3) return sqlite_ReturnWithError('near "'.$defparts[0].($defparts[1]?' '.$defparts[1]:'').($defparts[2]?' '.$defparts[2]:'').'": syntax error');
510- if($severpos = strpos($createtesttableSQL,' '.$defparts[1].' ')){
511- if($newcols[$defparts[1]] != $defparts[1]){
512- sqlite_ReturnWithError('unknown column "'.$defparts[1].'" in "'.$table.'"');
513- return false;
514- }
515- $newcols[$defparts[1]] = $defparts[2];
516- $nextcommapos = strpos($createtesttableSQL,',',$severpos);
517- $insertval = '';
518- for($i=2;$i<sizeof($defparts);$i++) $insertval.=' '.$defparts[$i];
519- if($nextcommapos) $createtesttableSQL = substr($createtesttableSQL,0,$severpos).$insertval.substr($createtesttableSQL,$nextcommapos);
520- else $createtesttableSQL = substr($createtesttableSQL,0,$severpos-(strpos($createtesttableSQL,',')?0:1)).$insertval.')';
521- } else return sqlite_ReturnWithError('unknown column "'.$defparts[1].'" in "'.$table.'"');
522- break;
523- case 'drop':
524- if(sizeof($defparts) < 2) return sqlite_ReturnWithError('near "'.$defparts[0].($defparts[1]?' '.$defparts[1]:'').'": syntax error');
525- if (sizeof($defparts)==3 && strtoupper($defparts[1])=='COLUMN'){
526- $defparts[1]=$defparts[2];
527- unset($defparts[2]);
528- }
529- $severpos = strpos($createtesttableSQL,' '.$defparts[1].' ');
530- if ($severpos===false) $severpos = strpos($createtesttableSQL," '".$defparts[1]."' ");
531- if($severpos){
532- $nextcommapos = strpos($createtesttableSQL,',',$severpos);
533- if($nextcommapos) $createtesttableSQL = substr($createtesttableSQL,0,$severpos).substr($createtesttableSQL,$nextcommapos + 1);
534- else $createtesttableSQL = substr($createtesttableSQL,0,$severpos-(strpos($createtesttableSQL,',')?0:1) - 1).')';
535- unset($newcols[$defparts[1]]);
536- } else return sqlite_ReturnWithError('unknown column "'.$defparts[1].'" in "'.$table.'"');
537- break;
538- default:
539- return sqlite_ReturnWithError('near "'.$prevword.'": syntax error');
540- break;
541- }
542- $prevword = $defparts[sizeof($defparts)-1];
543- }
544-
545- //this block of code generates a test table simply to verify that the columns specifed are valid in an sql statement
546- //this ensures that no reserved words are used as columns, for example
547- if (!sqlite_query($dbhandle,$createtesttableSQL)) return false;
548- $droptempsql = 'DROP TABLE '.$tmpname;
549- sqlite_query($dbhandle,$droptempsql);
550- //end block
551-
552- $createnewtableSQL = 'CREATE '.substr(trim(preg_replace("'".$tmpname."'",$table,$createtesttableSQL,1)),17);
553- $newcolumns = '';
554- $oldcolumns = '';
555- reset($newcols);
556- while(list($key,$val) = each($newcols)) {
557- if (strtoupper($val)!='PRIMARY' && strtoupper($key)!='PRIMARY' &&
558- strtoupper($val)!='UNIQUE' && strtoupper($key)!='UNIQUE'){
559- $newcolumns .= ($newcolumns?', ':'').$val;
560- $oldcolumns .= ($oldcolumns?', ':'').$key;
561- }
562- }
563- $copytonewsql = 'INSERT INTO '.$table.'('.$newcolumns.') SELECT '.$oldcolumns.' FROM '.$tmpname;
564-
565- sqlite_query($dbhandle,$createtemptableSQL); //create temp table
566- sqlite_query($dbhandle,$copytotempsql); //copy to table
567- sqlite_query($dbhandle,$dropoldsql); //drop old table
568-
569- sqlite_query($dbhandle,$createnewtableSQL); //recreate original table
570- foreach($createindexsql as $sql) sqlite_query($dbhandle,$sql); //recreate index
571- sqlite_query($dbhandle,$copytonewsql); //copy back to original table
572- sqlite_query($dbhandle,$droptempsql); //drop temp table
573-
574-/* echo '<p>'.$createtemptableSQL.'<p/>';
575- echo '<p>'.$copytotempsql.'<p/>';
576- echo '<p>'.$dropoldsql.'<p/>';
577- echo '<p>'.$createnewtableSQL.'<p/>';
578- echo '<p>'.$copytonewsql.'<p/>';
579- echo '<p>'.$droptempsql.'<p/>';
580-*/
581- return true;
582-}
583439 function _sqlite_divideByChar($char,$query,$limit=-1){
584440 if (!is_array($char)) $char=array($char);
585441 $ret=array();
@@ -596,7 +452,7 @@ function _sqlite_divideByChar($char,$query,$limit=-1){
596452 if (($k=strpos($query,"'"))===false) $k=strlen($query);
597453 if ($i<$j && $i<$k) {// ',' found
598454 $buff.=substr($query,0,$i);
599- if ($buff) $ret[]=$buff;
455+ if (strlen($buff)) $ret[]=$buff;
600456 $query=trim(substr($query,$i+1));
601457 $buff='';
602458 $limit--;
@@ -604,8 +460,8 @@ function _sqlite_divideByChar($char,$query,$limit=-1){
604460 } else if ($j<$i && $j<$k) {// '(' found
605461 if (($i=strpos($query,')',$j))===false) {
606462 $buff.=$query;
607- if ($buff) $ret[]=$buff;
608- $query='';
463+ if (strlen($buff)) $ret[]=$buff;
464+ $query=$buff='';
609465 } else {
610466 $buff.=substr($query,0,$i+1);
611467 $query=substr($query,$i+1);
@@ -613,23 +469,25 @@ function _sqlite_divideByChar($char,$query,$limit=-1){
613469 } else if ($k<$i && $k<$j) {// "'" found
614470 if (($i=strpos($query,"'",$k))===false) {
615471 $buff.=$query;
616- if ($buff) $ret[]=$buff;
617- $query='';
472+ if (strlen($buff)) $ret[]=$buff;
473+ $query=$buff='';
618474 } else {
619475 $buff.=substr($query,0,$i+1);
620476 $query=substr($query,$i+1);
621477 }
622478 } else {// last column
623479 $buff.=$query;
624- if ($buff) $ret[]=$buff;
625- $query='';
480+ if (strlen($buff)) $ret[]=$buff;
481+ $query=$buff='';
626482 }
627483 }
484+ if (strlen($buff)) $ret[]=$buff;
628485 return $ret;
629486 }
630487 function sqlite_showKeysFrom($tname,$dbhandle) {
631488 // This function is for supporing 'SHOW KEYS FROM' and 'SHOW INDEX FROM'.
632489 // For making the same result as obtained by MySQL, temporary table is made.
490+ if (preg_match('/^([^\s]+)\s+LIKE\s+\'([^\']+)\'$/i',$tname,$m)) list($m,$tname,$like)=$m;
633491 $tname=str_replace("'",'',$tname);
634492
635493 // Create a temporary table for making result
@@ -685,6 +543,7 @@ function sqlite_showKeysFrom($tname,$dbhandle) {
685543 }
686544 } else {// Non-primary key
687545 if (($name=str_replace("'",'',$a['name'])) && preg_match('/\(([\s\S]+)\)/',$sql,$matches)) {
546+ if (isset($like) && $name!=$like) continue;
688547 foreach(explode(',',$matches[1]) as $key=>$value) {
689548 $columnname=str_replace("'",'',$value);
690549 if (strpos(strtoupper($sql),'CREATE UNIQUE ')===0) $nonunique='0';
@@ -713,6 +572,7 @@ function sqlite_showKeysFrom($tname,$dbhandle) {
713572 function sqlite_showFieldsFrom($tname,$dbhandle){
714573 // This function is for supporing 'SHOW FIELDS FROM' and 'SHOW COLUMNS FROM'.
715574 // For making the same result as obtained by MySQL, temporary table is made.
575+ if (preg_match('/^([^\s]+)\s+LIKE\s+\'([^\']+)\'$/i',$tname,$m)) list($m,$tname,$like)=$m;
716576 $tname=str_replace("'",'',$tname);
717577
718578 // First, get the sql query when the table created
@@ -744,6 +604,7 @@ function sqlite_showFieldsFrom($tname,$dbhandle){
744604 // Check the table
745605 foreach($tablearray as $field=>$value) {
746606 if (strtoupper($field)=='PRIMARY') continue;//PRIMARY KEY('xx'[,'xx'])
607+ if (isset($like) && $field!=$like) continue;
747608 $uvalue=strtoupper($value.' ');
748609 $key=(string)$multi[$field];
749610 if ($uvalue=='INTEGER NOT NULL PRIMARY KEY ' || $uvalue=='INTEGER PRIMARY KEY ') {
--- /dev/null
+++ b/trunk/sqlite/nucleus/sqlite/sqlitealtertable.php
@@ -0,0 +1,160 @@
1+<?php
2+ /****************************************
3+ * SQLite-MySQL wrapper for Nucleus *
4+ * ver 0.8.6.0 *
5+ * Written by Katsumi *
6+ ****************************************/
7+
8+function sqlite_copytable($table,$newname,$dbhandle){
9+ // Note that indexes are not copied in this function.
10+ if (function_exists('microtime')) $tmptable='t'.str_replace(array(' ',','),'',microtime());
11+ // Getting information from original table and create new table
12+ $res = sqlite_query($dbhandle,"SELECT sql,name,type FROM sqlite_master WHERE tbl_name = '".$table."' ORDER BY type DESC");
13+ if(!sqlite_num_rows($res)) return sqlite_ReturnWithError('no such table: '.$table);
14+ while($row=sqlite_fetch_array($res,SQLITE_ASSOC)){
15+ if (!preg_match('/^([^\(]*)[\s]([^\(\']+)[\s]*\(([\s\S]*)$/',$row['sql'],$m) &&
16+ !preg_match('/^([^\(]*)[\s]\'([^\(]+)\'[\s]*\(([\s\S]*)$/',$row['sql'],$m)) return sqlite_ReturnWithError('unknown error');
17+ sqlite_query($dbhandle,$m[1]." '$newname'(".$m[3]);
18+ }
19+ // Copy the items
20+ sqlite_query($dbhandle,'BEGIN');
21+ $res=sqlite_unbuffered_query($dbhandle,"SELECT * FROM $table");
22+ while($row=sqlite_fetch_array($res,SQLITE_ASSOC)){
23+ $keys=$values=array();
24+ foreach($row as $key=>$value) {
25+ $keys[]="'$key'";
26+ $values[]="'".sqlite_escape_string($value)."'";
27+ }
28+ if (!sqlite_query($dbhandle,"INSERT INTO '$newname'(".implode(', ',$keys).') VALUES ('.implode(', ',$values).')')) {
29+ sqlite_query($dbhandle,'COMMIT');
30+ return false;
31+ }
32+ }
33+ sqlite_query($dbhandle,'COMMIT');
34+ $orgnum=sqlite_array_query($dbhandle,"SELECT COUNT(*) FROM $table");
35+ $newnum=sqlite_array_query($dbhandle,"SELECT COUNT(*) FROM $newname");
36+ if ($orgnum[0][0]!=$newnum[0][0]) return sqlite_ReturnWithError('Data transfer failed');
37+ return true;
38+}
39+function sqlite_altertable($table,$alterdefs,$dbhandle){
40+ // Almost completely re-written in February 2008.
41+ $table=str_replace("'",'',$table);
42+
43+ // Getting information from original table
44+ $res = sqlite_query($dbhandle,"SELECT sql,name,type FROM sqlite_master WHERE tbl_name = '".$table."' ORDER BY type DESC");
45+ if(!sqlite_num_rows($res)) return sqlite_ReturnWithError('no such table: '.$table);
46+ $orgindex=array();
47+ $row=sqlite_fetch_array($res,SQLITE_ASSOC); //table sql
48+ $orgsql=$row['sql'];
49+ while($row=sqlite_fetch_array($res,SQLITE_ASSOC)) $orgindex[strtolower($row['name'])]=$row['sql'];
50+ if (!preg_match('/^[^\(]+\((.*)\);*$/',$orgsql,$m)) return sqlite_ReturnWithError('unknown error');
51+ $orgtablearray=array();
52+ foreach(_sqlite_divideByChar(',',$orgtable=$m[1]) as $value){
53+ if (!preg_match('/^([^\s\']+)[\s]+([\s\S]*)$/',$value,$m) &&
54+ !preg_match('/^\'([^\']+)\'[\s]+([\s\S]*)$/',$value,$m)) return sqlite_ReturnWithError('unknown error');
55+ $orgtablearray[strtolower($m[1])]="'$m[1]' $m[2]";
56+ }
57+ $desttablearray=$orgtablearray;
58+ $destindex=$orgindex;
59+
60+ // Convert table
61+ foreach(_sqlite_divideByChar(',',$alterdefs) as $def){
62+ $def=_sqlite_divideByChar(array(' ',"\t","\r","\n"),trim($def));
63+ if (($c=count($def))<2) return sqlite_ReturnWithError('near "'.htmlspecialchars($def[0]).'": syntax error');
64+ // Check if FIRST/AFTER is used.
65+ // These are ignored in current version.
66+ $first=$after=false;
67+ if (strtoupper($def[$c-1])=='FIRST') {
68+ $first=true;
69+ array_pop($def);
70+ } elseif (strtoupper($def[$c-2])=='AFTER') {
71+ $after=array_pop($def);
72+ array_pop($def);
73+ }
74+ // ignore CONSTRAINT and COLUMN
75+ $method=strtoupper(array_shift($def));
76+ switch(strtoupper($def[0])){
77+ case 'CONSTRAINT': // delete two
78+ array_shift($def);
79+ case 'COLUMN': // delete one
80+ array_shift($def);
81+ default:
82+ break;
83+ }
84+ // The main routine of this function follow.
85+ switch($method){
86+ case 'MODIFY':
87+ case 'ALTER':
88+ if (error_reporting() & E_NOTICE) sqlite_ReturnWithError('ALTER/MODIFY is not supported');
89+ break;
90+ case 'DROP':
91+ case 'CHANGE':
92+ if (strtoupper($def[0])=='INDEX') {
93+ // delete index
94+ unset($destindex[strtolower($def[1])]);
95+ } else {
96+ // delete field
97+ unset($desttablearray[strtolower(str_replace("'",'',$def[0]))]);
98+ }
99+ if ($method!='CHANGE') break;
100+ case 'ADD':
101+ $field=array_shift($def);
102+ switch($submedthod=strtoupper($field)){
103+ case 'UNIQUE':
104+ case 'PRIMARY':
105+ case 'FOREIGN':
106+ case 'INDEX':
107+ case 'FULLTEXT':
108+ // add index
109+ if (strtoupper($index=array_shift($def))=='KEY') $index=array_shift($def);
110+ $def=implode(' ',$def);
111+ $destindex[strtolower(str_replace("'",'',$index))]=
112+ ($submedthod=='UNIQUE'?'CREATE UNIQUE INDEX ':'CREATE INDEX ').
113+ "$index ON '$table' $def";
114+ break;
115+ default:
116+ // add field
117+ $field=str_replace("'",'',$field);
118+ $desttablearray[strtolower($field)]="'$field' ".implode(' ',$def);
119+ }
120+ break;
121+ default:
122+ return sqlite_ReturnWithError('near "'.htmlspecialchars($method).'": syntax error');
123+ }
124+ }
125+
126+ // Create temporary table that has the modified field
127+ if (function_exists('microtime')) $tmptable='t'.str_replace(array(' ','.'),'',microtime());
128+ else $tmptable = 't'.rand(0,999999).time();
129+ $query="CREATE TABLE $tmptable (".implode(',',$desttablearray).')';
130+ if (!sqlite_query($dbhandle,$query)) return sqlite_ReturnWithError('Error: '.htmlspecialchars($query));
131+ // Copy the items
132+ sqlite_query($dbhandle,'BEGIN');
133+ $res=sqlite_unbuffered_query($dbhandle,"SELECT * FROM $table");
134+ while($row=sqlite_fetch_array($res,SQLITE_ASSOC)){
135+ $keys=$values=array();
136+ foreach($row as $key=>$value) {
137+ if (!isset($desttablearray[strtolower($key)])) continue;
138+ $keys[]="'$key'";
139+ $values[]="'".sqlite_escape_string($value)."'";
140+ }
141+ if (!sqlite_query($dbhandle,"INSERT INTO '$tmptable'(".implode(', ',$keys).') VALUES ('.implode(', ',$values).')')) {
142+ sqlite_query($dbhandle,'COMMIT');
143+ return false;
144+ }
145+ }
146+ sqlite_query($dbhandle,'COMMIT');
147+ $orgnum=sqlite_array_query($dbhandle,"SELECT COUNT(*) FROM $table");
148+ $tempnum=sqlite_array_query($dbhandle,"SELECT COUNT(*) FROM $tmptable");
149+ if ($orgnum[0][0]!=$tempnum[0][0]) return sqlite_ReturnWithError('Data transfer failed');
150+
151+ // New temporary table sccusfully made.
152+ // So, delete the original table and copy back the temporary table as original name.
153+ sqlite_query("DROP TABLE $table",$dbhandle);
154+ if (sqlite_copytable($tmptable,$table,$dbhandle)) sqlite_query("DROP TABLE $tmptable",$dbhandle);
155+
156+ // Add the indexes
157+ foreach($destindex as $index) sqlite_query($index,$dbhandle);
158+ return true;
159+}
160+?>
\ No newline at end of file
Show on old repository browser