Updated adodb syysext to upstream version 5.0.8a.
[Packages/TYPO3.CMS.git] / typo3 / sysext / adodb / adodb / adodb-datadict.inc.php
1 <?php
2
3 /**
4 V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
5 Released under both BSD license and Lesser GPL library license.
6 Whenever there is any discrepancy between the two licenses,
7 the BSD license will take precedence.
8
9 Set tabs to 4 for best viewing.
10
11 DOCUMENTATION:
12
13 See adodb/tests/test-datadict.php for docs and examples.
14 */
15
16 /*
17 Test script for parser
18 */
19
20 // security - hide paths
21 if (!defined('ADODB_DIR')) die();
22
23 function Lens_ParseTest()
24 {
25 $str = "`zcol ACOL` NUMBER(32,2) DEFAULT 'The \"cow\" (and Jim''s dog) jumps over the moon' PRIMARY, INTI INT AUTO DEFAULT 0, zcol2\"afs ds";
26 print "<p>$str</p>";
27 $a= Lens_ParseArgs($str);
28 print "<pre>";
29 print_r($a);
30 print "</pre>";
31 }
32
33
34 if (!function_exists('ctype_alnum')) {
35 function ctype_alnum($text) {
36 return preg_match('/^[a-z0-9]*$/i', $text);
37 }
38 }
39
40 //Lens_ParseTest();
41
42 /**
43 Parse arguments, treat "text" (text) and 'text' as quotation marks.
44 To escape, use "" or '' or ))
45
46 Will read in "abc def" sans quotes, as: abc def
47 Same with 'abc def'.
48 However if `abc def`, then will read in as `abc def`
49
50 @param endstmtchar Character that indicates end of statement
51 @param tokenchars Include the following characters in tokens apart from A-Z and 0-9
52 @returns 2 dimensional array containing parsed tokens.
53 */
54 function Lens_ParseArgs($args,$endstmtchar=',',$tokenchars='_.-')
55 {
56 $pos = 0;
57 $intoken = false;
58 $stmtno = 0;
59 $endquote = false;
60 $tokens = array();
61 $tokens[$stmtno] = array();
62 $max = strlen($args);
63 $quoted = false;
64 $tokarr = array();
65
66 while ($pos < $max) {
67 $ch = substr($args,$pos,1);
68 switch($ch) {
69 case ' ':
70 case "\t":
71 case "\n":
72 case "\r":
73 if (!$quoted) {
74 if ($intoken) {
75 $intoken = false;
76 $tokens[$stmtno][] = implode('',$tokarr);
77 }
78 break;
79 }
80
81 $tokarr[] = $ch;
82 break;
83
84 case '`':
85 if ($intoken) $tokarr[] = $ch;
86 case '(':
87 case ')':
88 case '"':
89 case "'":
90
91 if ($intoken) {
92 if (empty($endquote)) {
93 $tokens[$stmtno][] = implode('',$tokarr);
94 if ($ch == '(') $endquote = ')';
95 else $endquote = $ch;
96 $quoted = true;
97 $intoken = true;
98 $tokarr = array();
99 } else if ($endquote == $ch) {
100 $ch2 = substr($args,$pos+1,1);
101 if ($ch2 == $endquote) {
102 $pos += 1;
103 $tokarr[] = $ch2;
104 } else {
105 $quoted = false;
106 $intoken = false;
107 $tokens[$stmtno][] = implode('',$tokarr);
108 $endquote = '';
109 }
110 } else
111 $tokarr[] = $ch;
112
113 }else {
114
115 if ($ch == '(') $endquote = ')';
116 else $endquote = $ch;
117 $quoted = true;
118 $intoken = true;
119 $tokarr = array();
120 if ($ch == '`') $tokarr[] = '`';
121 }
122 break;
123
124 default:
125
126 if (!$intoken) {
127 if ($ch == $endstmtchar) {
128 $stmtno += 1;
129 $tokens[$stmtno] = array();
130 break;
131 }
132
133 $intoken = true;
134 $quoted = false;
135 $endquote = false;
136 $tokarr = array();
137
138 }
139
140 if ($quoted) $tokarr[] = $ch;
141 else if (ctype_alnum($ch) || strpos($tokenchars,$ch) !== false) $tokarr[] = $ch;
142 else {
143 if ($ch == $endstmtchar) {
144 $tokens[$stmtno][] = implode('',$tokarr);
145 $stmtno += 1;
146 $tokens[$stmtno] = array();
147 $intoken = false;
148 $tokarr = array();
149 break;
150 }
151 $tokens[$stmtno][] = implode('',$tokarr);
152 $tokens[$stmtno][] = $ch;
153 $intoken = false;
154 }
155 }
156 $pos += 1;
157 }
158 if ($intoken) $tokens[$stmtno][] = implode('',$tokarr);
159
160 return $tokens;
161 }
162
163
164 class ADODB_DataDict {
165 var $connection;
166 var $debug = false;
167 var $dropTable = 'DROP TABLE %s';
168 var $renameTable = 'RENAME TABLE %s TO %s';
169 var $dropIndex = 'DROP INDEX %s';
170 var $addCol = ' ADD';
171 var $alterCol = ' ALTER COLUMN';
172 var $dropCol = ' DROP COLUMN';
173 var $renameColumn = 'ALTER TABLE %s RENAME COLUMN %s TO %s'; // table, old-column, new-column, column-definitions (not used by default)
174 var $nameRegex = '\w';
175 var $nameRegexBrackets = 'a-zA-Z0-9_\(\)';
176 var $schema = false;
177 var $serverInfo = array();
178 var $autoIncrement = false;
179 var $dataProvider;
180 var $invalidResizeTypes4 = array('CLOB','BLOB','TEXT','DATE','TIME'); // for changetablesql
181 var $blobSize = 100; /// any varchar/char field this size or greater is treated as a blob
182 /// in other words, we use a text area for editting.
183
184 function GetCommentSQL($table,$col)
185 {
186 return false;
187 }
188
189 function SetCommentSQL($table,$col,$cmt)
190 {
191 return false;
192 }
193
194 function MetaTables()
195 {
196 if (!$this->connection->IsConnected()) return array();
197 return $this->connection->MetaTables();
198 }
199
200 function MetaColumns($tab, $upper=true, $schema=false)
201 {
202 if (!$this->connection->IsConnected()) return array();
203 return $this->connection->MetaColumns($this->TableName($tab), $upper, $schema);
204 }
205
206 function MetaPrimaryKeys($tab,$owner=false,$intkey=false)
207 {
208 if (!$this->connection->IsConnected()) return array();
209 return $this->connection->MetaPrimaryKeys($this->TableName($tab), $owner, $intkey);
210 }
211
212 function MetaIndexes($table, $primary = false, $owner = false)
213 {
214 if (!$this->connection->IsConnected()) return array();
215 return $this->connection->MetaIndexes($this->TableName($table), $primary, $owner);
216 }
217
218 function MetaType($t,$len=-1,$fieldobj=false)
219 {
220 static $typeMap = array(
221 'VARCHAR' => 'C',
222 'VARCHAR2' => 'C',
223 'CHAR' => 'C',
224 'C' => 'C',
225 'STRING' => 'C',
226 'NCHAR' => 'C',
227 'NVARCHAR' => 'C',
228 'VARYING' => 'C',
229 'BPCHAR' => 'C',
230 'CHARACTER' => 'C',
231 'INTERVAL' => 'C', # Postgres
232 'MACADDR' => 'C', # postgres
233 'VAR_STRING' => 'C', # mysql
234 ##
235 'LONGCHAR' => 'X',
236 'TEXT' => 'X',
237 'NTEXT' => 'X',
238 'M' => 'X',
239 'X' => 'X',
240 'CLOB' => 'X',
241 'NCLOB' => 'X',
242 'LVARCHAR' => 'X',
243 ##
244 'BLOB' => 'B',
245 'IMAGE' => 'B',
246 'BINARY' => 'B',
247 'VARBINARY' => 'B',
248 'LONGBINARY' => 'B',
249 'B' => 'B',
250 ##
251 'YEAR' => 'D', // mysql
252 'DATE' => 'D',
253 'D' => 'D',
254 ##
255 'UNIQUEIDENTIFIER' => 'C', # MS SQL Server
256 ##
257 'TIME' => 'T',
258 'TIMESTAMP' => 'T',
259 'DATETIME' => 'T',
260 'TIMESTAMPTZ' => 'T',
261 'SMALLDATETIME' => 'T',
262 'T' => 'T',
263 'TIMESTAMP WITHOUT TIME ZONE' => 'T', // postgresql
264 ##
265 'BOOL' => 'L',
266 'BOOLEAN' => 'L',
267 'BIT' => 'L',
268 'L' => 'L',
269 ##
270 'COUNTER' => 'R',
271 'R' => 'R',
272 'SERIAL' => 'R', // ifx
273 'INT IDENTITY' => 'R',
274 ##
275 'INT' => 'I',
276 'INT2' => 'I',
277 'INT4' => 'I',
278 'INT8' => 'I',
279 'INTEGER' => 'I',
280 'INTEGER UNSIGNED' => 'I',
281 'SHORT' => 'I',
282 'TINYINT' => 'I',
283 'SMALLINT' => 'I',
284 'I' => 'I',
285 ##
286 'LONG' => 'N', // interbase is numeric, oci8 is blob
287 'BIGINT' => 'N', // this is bigger than PHP 32-bit integers
288 'DECIMAL' => 'N',
289 'DEC' => 'N',
290 'REAL' => 'N',
291 'DOUBLE' => 'N',
292 'DOUBLE PRECISION' => 'N',
293 'SMALLFLOAT' => 'N',
294 'FLOAT' => 'N',
295 'NUMBER' => 'N',
296 'NUM' => 'N',
297 'NUMERIC' => 'N',
298 'MONEY' => 'N',
299
300 ## informix 9.2
301 'SQLINT' => 'I',
302 'SQLSERIAL' => 'I',
303 'SQLSMINT' => 'I',
304 'SQLSMFLOAT' => 'N',
305 'SQLFLOAT' => 'N',
306 'SQLMONEY' => 'N',
307 'SQLDECIMAL' => 'N',
308 'SQLDATE' => 'D',
309 'SQLVCHAR' => 'C',
310 'SQLCHAR' => 'C',
311 'SQLDTIME' => 'T',
312 'SQLINTERVAL' => 'N',
313 'SQLBYTES' => 'B',
314 'SQLTEXT' => 'X',
315 ## informix 10
316 "SQLINT8" => 'I8',
317 "SQLSERIAL8" => 'I8',
318 "SQLNCHAR" => 'C',
319 "SQLNVCHAR" => 'C',
320 "SQLLVARCHAR" => 'X',
321 "SQLBOOL" => 'L'
322 );
323
324 if (!$this->connection->IsConnected()) {
325 $t = strtoupper($t);
326 if (isset($typeMap[$t])) return $typeMap[$t];
327 return 'N';
328 }
329 return $this->connection->MetaType($t,$len,$fieldobj);
330 }
331
332 function NameQuote($name = NULL,$allowBrackets=false)
333 {
334 if (!is_string($name)) {
335 return FALSE;
336 }
337
338 $name = trim($name);
339
340 if ( !is_object($this->connection) ) {
341 return $name;
342 }
343
344 $quote = $this->connection->nameQuote;
345
346 // if name is of the form `name`, quote it
347 if ( preg_match('/^`(.+)`$/', $name, $matches) ) {
348 return $quote . $matches[1] . $quote;
349 }
350
351 // if name contains special characters, quote it
352 $regex = ($allowBrackets) ? $this->nameRegexBrackets : $this->nameRegex;
353
354 if ( !preg_match('/^[' . $regex . ']+$/', $name) ) {
355 return $quote . $name . $quote;
356 }
357
358 return $name;
359 }
360
361 function TableName($name)
362 {
363 if ( $this->schema ) {
364 return $this->NameQuote($this->schema) .'.'. $this->NameQuote($name);
365 }
366 return $this->NameQuote($name);
367 }
368
369 // Executes the sql array returned by GetTableSQL and GetIndexSQL
370 function ExecuteSQLArray($sql, $continueOnError = true)
371 {
372 $rez = 2;
373 $conn = $this->connection;
374 $saved = $conn->debug;
375 foreach($sql as $line) {
376
377 if ($this->debug) $conn->debug = true;
378 $ok = $conn->Execute($line);
379 $conn->debug = $saved;
380 if (!$ok) {
381 if ($this->debug) ADOConnection::outp($conn->ErrorMsg());
382 if (!$continueOnError) return 0;
383 $rez = 1;
384 }
385 }
386 return $rez;
387 }
388
389 /**
390 Returns the actual type given a character code.
391
392 C: varchar
393 X: CLOB (character large object) or largest varchar size if CLOB is not supported
394 C2: Multibyte varchar
395 X2: Multibyte CLOB
396
397 B: BLOB (binary large object)
398
399 D: Date
400 T: Date-time
401 L: Integer field suitable for storing booleans (0 or 1)
402 I: Integer
403 F: Floating point number
404 N: Numeric or decimal number
405 */
406
407 function ActualType($meta)
408 {
409 return $meta;
410 }
411
412 function CreateDatabase($dbname,$options=false)
413 {
414 $options = $this->_Options($options);
415 $sql = array();
416
417 $s = 'CREATE DATABASE ' . $this->NameQuote($dbname);
418 if (isset($options[$this->upperName]))
419 $s .= ' '.$options[$this->upperName];
420
421 $sql[] = $s;
422 return $sql;
423 }
424
425 /*
426 Generates the SQL to create index. Returns an array of sql strings.
427 */
428 function CreateIndexSQL($idxname, $tabname, $flds, $idxoptions = false)
429 {
430 if (!is_array($flds)) {
431 $flds = explode(',',$flds);
432 }
433
434 foreach($flds as $key => $fld) {
435 # some indexes can use partial fields, eg. index first 32 chars of "name" with NAME(32)
436 $flds[$key] = $this->NameQuote($fld,$allowBrackets=true);
437 }
438
439 return $this->_IndexSQL($this->NameQuote($idxname), $this->TableName($tabname), $flds, $this->_Options($idxoptions));
440 }
441
442 function DropIndexSQL ($idxname, $tabname = NULL)
443 {
444 return array(sprintf($this->dropIndex, $this->NameQuote($idxname), $this->TableName($tabname)));
445 }
446
447 function SetSchema($schema)
448 {
449 $this->schema = $schema;
450 }
451
452 function AddColumnSQL($tabname, $flds)
453 {
454 $tabname = $this->TableName ($tabname);
455 $sql = array();
456 list($lines,$pkey,$idxs) = $this->_GenFields($flds);
457 // genfields can return FALSE at times
458 if ($lines == null) $lines = array();
459 $alter = 'ALTER TABLE ' . $tabname . $this->addCol . ' ';
460 foreach($lines as $v) {
461 $sql[] = $alter . $v;
462 }
463 if (is_array($idxs)) {
464 foreach($idxs as $idx => $idxdef) {
465 $sql_idxs = $this->CreateIndexSql($idx, $tabname, $idxdef['cols'], $idxdef['opts']);
466 $sql = array_merge($sql, $sql_idxs);
467 }
468 }
469 return $sql;
470 }
471
472 /**
473 * Change the definition of one column
474 *
475 * As some DBM's can't do that on there own, you need to supply the complete defintion of the new table,
476 * to allow, recreating the table and copying the content over to the new table
477 * @param string $tabname table-name
478 * @param string $flds column-name and type for the changed column
479 * @param string $tableflds='' complete defintion of the new table, eg. for postgres, default ''
480 * @param array/string $tableoptions='' options for the new table see CreateTableSQL, default ''
481 * @return array with SQL strings
482 */
483 function AlterColumnSQL($tabname, $flds, $tableflds='',$tableoptions='')
484 {
485 $tabname = $this->TableName ($tabname);
486 $sql = array();
487 list($lines,$pkey,$idxs) = $this->_GenFields($flds);
488 // genfields can return FALSE at times
489 if ($lines == null) $lines = array();
490 $alter = 'ALTER TABLE ' . $tabname . $this->alterCol . ' ';
491 foreach($lines as $v) {
492 $sql[] = $alter . $v;
493 }
494 if (is_array($idxs)) {
495 foreach($idxs as $idx => $idxdef) {
496 $sql_idxs = $this->CreateIndexSql($idx, $tabname, $idxdef['cols'], $idxdef['opts']);
497 $sql = array_merge($sql, $sql_idxs);
498 }
499
500 }
501 return $sql;
502 }
503
504 /**
505 * Rename one column
506 *
507 * Some DBM's can only do this together with changeing the type of the column (even if that stays the same, eg. mysql)
508 * @param string $tabname table-name
509 * @param string $oldcolumn column-name to be renamed
510 * @param string $newcolumn new column-name
511 * @param string $flds='' complete column-defintion-string like for AddColumnSQL, only used by mysql atm., default=''
512 * @return array with SQL strings
513 */
514 function RenameColumnSQL($tabname,$oldcolumn,$newcolumn,$flds='')
515 {
516 $tabname = $this->TableName ($tabname);
517 if ($flds) {
518 list($lines,$pkey,$idxs) = $this->_GenFields($flds);
519 // genfields can return FALSE at times
520 if ($lines == null) $lines = array();
521 list(,$first) = each($lines);
522 list(,$column_def) = split("[\t ]+",$first,2);
523 }
524 return array(sprintf($this->renameColumn,$tabname,$this->NameQuote($oldcolumn),$this->NameQuote($newcolumn),$column_def));
525 }
526
527 /**
528 * Drop one column
529 *
530 * Some DBM's can't do that on there own, you need to supply the complete defintion of the new table,
531 * to allow, recreating the table and copying the content over to the new table
532 * @param string $tabname table-name
533 * @param string $flds column-name and type for the changed column
534 * @param string $tableflds='' complete defintion of the new table, eg. for postgres, default ''
535 * @param array/string $tableoptions='' options for the new table see CreateTableSQL, default ''
536 * @return array with SQL strings
537 */
538 function DropColumnSQL($tabname, $flds, $tableflds='',$tableoptions='')
539 {
540 $tabname = $this->TableName ($tabname);
541 if (!is_array($flds)) $flds = explode(',',$flds);
542 $sql = array();
543 $alter = 'ALTER TABLE ' . $tabname . $this->dropCol . ' ';
544 foreach($flds as $v) {
545 $sql[] = $alter . $this->NameQuote($v);
546 }
547 return $sql;
548 }
549
550 function DropTableSQL($tabname)
551 {
552 return array (sprintf($this->dropTable, $this->TableName($tabname)));
553 }
554
555 function RenameTableSQL($tabname,$newname)
556 {
557 return array (sprintf($this->renameTable, $this->TableName($tabname),$this->TableName($newname)));
558 }
559
560 /**
561 Generate the SQL to create table. Returns an array of sql strings.
562 */
563 function CreateTableSQL($tabname, $flds, $tableoptions=array())
564 {
565 list($lines,$pkey,$idxs) = $this->_GenFields($flds, true);
566 // genfields can return FALSE at times
567 if ($lines == null) $lines = array();
568
569 $taboptions = $this->_Options($tableoptions);
570 $tabname = $this->TableName ($tabname);
571 $sql = $this->_TableSQL($tabname,$lines,$pkey,$taboptions);
572
573 // ggiunta - 2006/10/12 - KLUDGE:
574 // if we are on autoincrement, and table options includes REPLACE, the
575 // autoincrement sequence has already been dropped on table creation sql, so
576 // we avoid passing REPLACE to trigger creation code. This prevents
577 // creating sql that double-drops the sequence
578 if ($this->autoIncrement && isset($taboptions['REPLACE']))
579 unset($taboptions['REPLACE']);
580 $tsql = $this->_Triggers($tabname,$taboptions);
581 foreach($tsql as $s) $sql[] = $s;
582
583 if (is_array($idxs)) {
584 foreach($idxs as $idx => $idxdef) {
585 $sql_idxs = $this->CreateIndexSql($idx, $tabname, $idxdef['cols'], $idxdef['opts']);
586 $sql = array_merge($sql, $sql_idxs);
587 }
588 }
589
590 return $sql;
591 }
592
593 function _GenFields($flds,$widespacing=false)
594 {
595 if (is_string($flds)) {
596 $padding = ' ';
597 $txt = $flds.$padding;
598 $flds = array();
599 $flds0 = Lens_ParseArgs($txt,',');
600 $hasparam = false;
601 foreach($flds0 as $f0) {
602 $f1 = array();
603 foreach($f0 as $token) {
604 switch (strtoupper($token)) {
605 case 'INDEX':
606 $f1['INDEX'] = '';
607 // fall through intentionally
608 case 'CONSTRAINT':
609 case 'DEFAULT':
610 $hasparam = $token;
611 break;
612 default:
613 if ($hasparam) $f1[$hasparam] = $token;
614 else $f1[] = $token;
615 $hasparam = false;
616 break;
617 }
618 }
619 // 'index' token without a name means single column index: name it after column
620 if (array_key_exists('INDEX', $f1) && $f1['INDEX'] == '') {
621 $f1['INDEX'] = isset($f0['NAME']) ? $f0['NAME'] : $f0[0];
622 // check if column name used to create an index name was quoted
623 if (($f1['INDEX'][0] == '"' || $f1['INDEX'][0] == "'" || $f1['INDEX'][0] == "`") &&
624 ($f1['INDEX'][0] == substr($f1['INDEX'], -1))) {
625 $f1['INDEX'] = $f1['INDEX'][0].'idx_'.substr($f1['INDEX'], 1, -1).$f1['INDEX'][0];
626 }
627 else
628 $f1['INDEX'] = 'idx_'.$f1['INDEX'];
629 }
630 // reset it, so we don't get next field 1st token as INDEX...
631 $hasparam = false;
632
633 $flds[] = $f1;
634
635 }
636 }
637 $this->autoIncrement = false;
638 $lines = array();
639 $pkey = array();
640 $idxs = array();
641 foreach($flds as $fld) {
642 $fld = _array_change_key_case($fld);
643
644 $fname = false;
645 $fdefault = false;
646 $fautoinc = false;
647 $ftype = false;
648 $fsize = false;
649 $fprec = false;
650 $fprimary = false;
651 $fnoquote = false;
652 $fdefts = false;
653 $fdefdate = false;
654 $fconstraint = false;
655 $fnotnull = false;
656 $funsigned = false;
657 $findex = '';
658 $funiqueindex = false;
659
660 //-----------------
661 // Parse attributes
662 foreach($fld as $attr => $v) {
663 if ($attr == 2 && is_numeric($v)) $attr = 'SIZE';
664 else if (is_numeric($attr) && $attr > 1 && !is_numeric($v)) $attr = strtoupper($v);
665
666 switch($attr) {
667 case '0':
668 case 'NAME': $fname = $v; break;
669 case '1':
670 case 'TYPE': $ty = $v; $ftype = $this->ActualType(strtoupper($v)); break;
671
672 case 'SIZE':
673 $dotat = strpos($v,'.'); if ($dotat === false) $dotat = strpos($v,',');
674 if ($dotat === false) $fsize = $v;
675 else {
676 $fsize = substr($v,0,$dotat);
677 $fprec = substr($v,$dotat+1);
678 }
679 break;
680 case 'UNSIGNED': $funsigned = true; break;
681 case 'AUTOINCREMENT':
682 case 'AUTO': $fautoinc = true; $fnotnull = true; break;
683 case 'KEY':
684 // a primary key col can be non unique in itself (if key spans many cols...)
685 case 'PRIMARY': $fprimary = $v; $fnotnull = true; /*$funiqueindex = true;*/ break;
686 case 'DEF':
687 case 'DEFAULT': $fdefault = $v; break;
688 case 'NOTNULL': $fnotnull = $v; break;
689 case 'NOQUOTE': $fnoquote = $v; break;
690 case 'DEFDATE': $fdefdate = $v; break;
691 case 'DEFTIMESTAMP': $fdefts = $v; break;
692 case 'CONSTRAINT': $fconstraint = $v; break;
693 // let INDEX keyword create a 'very standard' index on column
694 case 'INDEX': $findex = $v; break;
695 case 'UNIQUE': $funiqueindex = true; break;
696 } //switch
697 } // foreach $fld
698
699 //--------------------
700 // VALIDATE FIELD INFO
701 if (!strlen($fname)) {
702 if ($this->debug) ADOConnection::outp("Undefined NAME");
703 return false;
704 }
705
706 $fid = strtoupper(preg_replace('/^`(.+)`$/', '$1', $fname));
707 $fname = $this->NameQuote($fname);
708
709 if (!strlen($ftype)) {
710 if ($this->debug) ADOConnection::outp("Undefined TYPE for field '$fname'");
711 return false;
712 } else {
713 $ftype = strtoupper($ftype);
714 }
715
716 $ftype = $this->_GetSize($ftype, $ty, $fsize, $fprec);
717
718 if ($ty == 'X' || $ty == 'X2' || $ty == 'B') $fnotnull = false; // some blob types do not accept nulls
719
720 if ($fprimary) $pkey[] = $fname;
721
722 // some databases do not allow blobs to have defaults
723 if ($ty == 'X') $fdefault = false;
724
725 // build list of indexes
726 if ($findex != '') {
727 if (array_key_exists($findex, $idxs)) {
728 $idxs[$findex]['cols'][] = ($fname);
729 if (in_array('UNIQUE', $idxs[$findex]['opts']) != $funiqueindex) {
730 if ($this->debug) ADOConnection::outp("Index $findex defined once UNIQUE and once not");
731 }
732 if ($funiqueindex && !in_array('UNIQUE', $idxs[$findex]['opts']))
733 $idxs[$findex]['opts'][] = 'UNIQUE';
734 }
735 else
736 {
737 $idxs[$findex] = array();
738 $idxs[$findex]['cols'] = array($fname);
739 if ($funiqueindex)
740 $idxs[$findex]['opts'] = array('UNIQUE');
741 else
742 $idxs[$findex]['opts'] = array();
743 }
744 }
745
746 //--------------------
747 // CONSTRUCT FIELD SQL
748 if ($fdefts) {
749 if (substr($this->connection->databaseType,0,5) == 'mysql') {
750 $ftype = 'TIMESTAMP';
751 } else {
752 $fdefault = $this->connection->sysTimeStamp;
753 }
754 } else if ($fdefdate) {
755 if (substr($this->connection->databaseType,0,5) == 'mysql') {
756 $ftype = 'TIMESTAMP';
757 } else {
758 $fdefault = $this->connection->sysDate;
759 }
760 } else if ($fdefault !== false && !$fnoquote) {
761 if ($ty == 'C' or $ty == 'X' or
762 ( substr($fdefault,0,1) != "'" && !is_numeric($fdefault))) {
763
764 if (($ty == 'D' || $ty == 'T') && strtolower($fdefault) != 'null') {
765 // convert default date into database-aware code
766 if ($ty == 'T')
767 {
768 $fdefault = $this->connection->DBTimeStamp($fdefault);
769 }
770 else
771 {
772 $fdefault = $this->connection->DBDate($fdefault);
773 }
774 }
775 else
776 if (strlen($fdefault) != 1 && substr($fdefault,0,1) == ' ' && substr($fdefault,strlen($fdefault)-1) == ' ')
777 $fdefault = trim($fdefault);
778 else if (strtolower($fdefault) != 'null')
779 $fdefault = $this->connection->qstr($fdefault);
780 }
781 }
782 $suffix = $this->_CreateSuffix($fname,$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint,$funsigned);
783
784 // add index creation
785 if ($widespacing) $fname = str_pad($fname,24);
786
787 // check for field names appearing twice
788 if (array_key_exists($fid, $lines)) {
789 ADOConnection::outp("Field '$fname' defined twice");
790 }
791
792 $lines[$fid] = $fname.' '.$ftype.$suffix;
793
794 if ($fautoinc) $this->autoIncrement = true;
795 } // foreach $flds
796
797 return array($lines,$pkey,$idxs);
798 }
799
800 /**
801 GENERATE THE SIZE PART OF THE DATATYPE
802 $ftype is the actual type
803 $ty is the type defined originally in the DDL
804 */
805 function _GetSize($ftype, $ty, $fsize, $fprec)
806 {
807 if (strlen($fsize) && $ty != 'X' && $ty != 'B' && strpos($ftype,'(') === false) {
808 $ftype .= "(".$fsize;
809 if (strlen($fprec)) $ftype .= ",".$fprec;
810 $ftype .= ')';
811 }
812 return $ftype;
813 }
814
815
816 // return string must begin with space
817 function _CreateSuffix($fname,&$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint,$funsigned)
818 {
819 $suffix = '';
820 if (strlen($fdefault)) $suffix .= " DEFAULT $fdefault";
821 if ($fnotnull) $suffix .= ' NOT NULL';
822 if ($fconstraint) $suffix .= ' '.$fconstraint;
823 return $suffix;
824 }
825
826 function _IndexSQL($idxname, $tabname, $flds, $idxoptions)
827 {
828 $sql = array();
829
830 if ( isset($idxoptions['REPLACE']) || isset($idxoptions['DROP']) ) {
831 $sql[] = sprintf ($this->dropIndex, $idxname);
832 if ( isset($idxoptions['DROP']) )
833 return $sql;
834 }
835
836 if ( empty ($flds) ) {
837 return $sql;
838 }
839
840 $unique = isset($idxoptions['UNIQUE']) ? ' UNIQUE' : '';
841
842 $s = 'CREATE' . $unique . ' INDEX ' . $idxname . ' ON ' . $tabname . ' ';
843
844 if ( isset($idxoptions[$this->upperName]) )
845 $s .= $idxoptions[$this->upperName];
846
847 if ( is_array($flds) )
848 $flds = implode(', ',$flds);
849 $s .= '(' . $flds . ')';
850 $sql[] = $s;
851
852 return $sql;
853 }
854
855 function _DropAutoIncrement($tabname)
856 {
857 return false;
858 }
859
860 function _TableSQL($tabname,$lines,$pkey,$tableoptions)
861 {
862 $sql = array();
863
864 if (isset($tableoptions['REPLACE']) || isset ($tableoptions['DROP'])) {
865 $sql[] = sprintf($this->dropTable,$tabname);
866 if ($this->autoIncrement) {
867 $sInc = $this->_DropAutoIncrement($tabname);
868 if ($sInc) $sql[] = $sInc;
869 }
870 if ( isset ($tableoptions['DROP']) ) {
871 return $sql;
872 }
873 }
874 $s = "CREATE TABLE $tabname (\n";
875 $s .= implode(",\n", $lines);
876 if (sizeof($pkey)>0) {
877 $s .= ",\n PRIMARY KEY (";
878 $s .= implode(", ",$pkey).")";
879 }
880 if (isset($tableoptions['CONSTRAINTS']))
881 $s .= "\n".$tableoptions['CONSTRAINTS'];
882
883 if (isset($tableoptions[$this->upperName.'_CONSTRAINTS']))
884 $s .= "\n".$tableoptions[$this->upperName.'_CONSTRAINTS'];
885
886 $s .= "\n)";
887 if (isset($tableoptions[$this->upperName])) $s .= $tableoptions[$this->upperName];
888 $sql[] = $s;
889
890 return $sql;
891 }
892
893 /**
894 GENERATE TRIGGERS IF NEEDED
895 used when table has auto-incrementing field that is emulated using triggers
896 */
897 function _Triggers($tabname,$taboptions)
898 {
899 return array();
900 }
901
902 /**
903 Sanitize options, so that array elements with no keys are promoted to keys
904 */
905 function _Options($opts)
906 {
907 if (!is_array($opts)) return array();
908 $newopts = array();
909 foreach($opts as $k => $v) {
910 if (is_numeric($k)) $newopts[strtoupper($v)] = $v;
911 else $newopts[strtoupper($k)] = $v;
912 }
913 return $newopts;
914 }
915
916 /**
917 "Florian Buzin [ easywe ]" <florian.buzin#easywe.de>
918
919 This function changes/adds new fields to your table. You don't
920 have to know if the col is new or not. It will check on its own.
921 */
922 function ChangeTableSQL($tablename, $flds, $tableoptions = false, $dropOldFlds=false)
923 {
924 global $ADODB_FETCH_MODE;
925
926 $save = $ADODB_FETCH_MODE;
927 $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
928 if ($this->connection->fetchMode !== false) $savem = $this->connection->SetFetchMode(false);
929
930 // check table exists
931 $save_handler = $this->connection->raiseErrorFn;
932 $this->connection->raiseErrorFn = '';
933 $cols = $this->MetaColumns($tablename);
934 $this->connection->raiseErrorFn = $save_handler;
935
936 if (isset($savem)) $this->connection->SetFetchMode($savem);
937 $ADODB_FETCH_MODE = $save;
938
939 if ( empty($cols)) {
940 return $this->CreateTableSQL($tablename, $flds, $tableoptions);
941 }
942
943 if (is_array($flds)) {
944 // Cycle through the update fields, comparing
945 // existing fields to fields to update.
946 // if the Metatype and size is exactly the
947 // same, ignore - by Mark Newham
948 $holdflds = array();
949 foreach($flds as $k=>$v) {
950 if ( isset($cols[$k]) && is_object($cols[$k]) ) {
951 // If already not allowing nulls, then don't change
952 $obj = $cols[$k];
953 if (isset($obj->not_null) && $obj->not_null)
954 $v = str_replace('NOT NULL','',$v);
955 if (isset($obj->auto_increment) && $obj->auto_increment && empty($v['AUTOINCREMENT']))
956 $v = str_replace('AUTOINCREMENT','',$v);
957
958 $c = $cols[$k];
959 $ml = $c->max_length;
960 $mt = $this->MetaType($c->type,$ml);
961 if ($ml == -1) $ml = '';
962 if ($mt == 'X') $ml = $v['SIZE'];
963 if (($mt != $v['TYPE']) || $ml != $v['SIZE'] || (isset($v['AUTOINCREMENT']) && $v['AUTOINCREMENT'] != $obj->auto_increment)) {
964 $holdflds[$k] = $v;
965 }
966 } else {
967 $holdflds[$k] = $v;
968 }
969 }
970 $flds = $holdflds;
971 }
972
973
974 // already exists, alter table instead
975 list($lines,$pkey,$idxs) = $this->_GenFields($flds);
976 // genfields can return FALSE at times
977 if ($lines == null) $lines = array();
978 $alter = 'ALTER TABLE ' . $this->TableName($tablename);
979 $sql = array();
980
981 foreach ( $lines as $id => $v ) {
982 if ( isset($cols[$id]) && is_object($cols[$id]) ) {
983
984 $flds = Lens_ParseArgs($v,',');
985
986 // We are trying to change the size of the field, if not allowed, simply ignore the request.
987 // $flds[1] holds the type, $flds[2] holds the size -postnuke addition
988 if ($flds && in_array(strtoupper(substr($flds[0][1],0,4)),$this->invalidResizeTypes4)
989 && (isset($flds[0][2]) && is_numeric($flds[0][2]))) {
990 if ($this->debug) ADOConnection::outp(sprintf("<h3>%s cannot be changed to %s currently</h3>", $flds[0][0], $flds[0][1]));
991 #echo "<h3>$this->alterCol cannot be changed to $flds currently</h3>";
992 continue;
993 }
994 $sql[] = $alter . $this->alterCol . ' ' . $v;
995 } else {
996 $sql[] = $alter . $this->addCol . ' ' . $v;
997 }
998 }
999
1000 if ($dropOldFlds) {
1001 foreach ( $cols as $id => $v )
1002 if ( !isset($lines[$id]) )
1003 $sql[] = $alter . $this->dropCol . ' ' . $v->name;
1004 }
1005 return $sql;
1006 }
1007 } // class
1008 ?>