PageRenderTime 63ms CodeModel.GetById 31ms RepoModel.GetById 0ms app.codeStats 0ms

/concrete/libraries/3rdparty/adodb/adodb-datadict.inc.php

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