PageRenderTime 57ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 0ms

/05_Desarrollo/lib/adodb/adodb-datadict.inc.php

https://bitbucket.org/SerafinAkatsuki/consultorio
PHP | 1000 lines | 980 code | 4 blank | 16 comment | 1 complexity | 8d4a4ab8d5149d813a78ffcdeaace632 MD5 | raw file
Possible License(s): LGPL-2.1
  1. <?php
  2. /**
  3. V4.990 11 July 2008 (c) 2000-2008 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. ##
  200. 'LONGCHAR' => 'X',
  201. 'TEXT' => 'X',
  202. 'NTEXT' => 'X',
  203. 'M' => 'X',
  204. 'X' => 'X',
  205. 'CLOB' => 'X',
  206. 'NCLOB' => 'X',
  207. 'LVARCHAR' => 'X',
  208. ##
  209. 'BLOB' => 'B',
  210. 'IMAGE' => 'B',
  211. 'BINARY' => 'B',
  212. 'VARBINARY' => 'B',
  213. 'LONGBINARY' => 'B',
  214. 'B' => 'B',
  215. ##
  216. 'YEAR' => 'D', // mysql
  217. 'DATE' => 'D',
  218. 'D' => 'D',
  219. ##
  220. 'UNIQUEIDENTIFIER' => 'C', # MS SQL Server
  221. ##
  222. 'TIME' => 'T',
  223. 'TIMESTAMP' => 'T',
  224. 'DATETIME' => 'T',
  225. 'TIMESTAMPTZ' => 'T',
  226. 'T' => 'T',
  227. 'TIMESTAMP WITHOUT TIME ZONE' => 'T', // postgresql
  228. ##
  229. 'BOOL' => 'L',
  230. 'BOOLEAN' => 'L',
  231. 'BIT' => 'L',
  232. 'L' => 'L',
  233. ##
  234. 'COUNTER' => 'R',
  235. 'R' => 'R',
  236. 'SERIAL' => 'R', // ifx
  237. 'INT IDENTITY' => 'R',
  238. ##
  239. 'INT' => 'I',
  240. 'INT2' => 'I',
  241. 'INT4' => 'I',
  242. 'INT8' => 'I',
  243. 'INTEGER' => 'I',
  244. 'INTEGER UNSIGNED' => 'I',
  245. 'SHORT' => 'I',
  246. 'TINYINT' => 'I',
  247. 'SMALLINT' => 'I',
  248. 'I' => 'I',
  249. ##
  250. 'LONG' => 'N', // interbase is numeric, oci8 is blob
  251. 'BIGINT' => 'N', // this is bigger than PHP 32-bit integers
  252. 'DECIMAL' => 'N',
  253. 'DEC' => 'N',
  254. 'REAL' => 'N',
  255. 'DOUBLE' => 'N',
  256. 'DOUBLE PRECISION' => 'N',
  257. 'SMALLFLOAT' => 'N',
  258. 'FLOAT' => 'N',
  259. 'NUMBER' => 'N',
  260. 'NUM' => 'N',
  261. 'NUMERIC' => 'N',
  262. 'MONEY' => 'N',
  263. ## informix 9.2
  264. 'SQLINT' => 'I',
  265. 'SQLSERIAL' => 'I',
  266. 'SQLSMINT' => 'I',
  267. 'SQLSMFLOAT' => 'N',
  268. 'SQLFLOAT' => 'N',
  269. 'SQLMONEY' => 'N',
  270. 'SQLDECIMAL' => 'N',
  271. 'SQLDATE' => 'D',
  272. 'SQLVCHAR' => 'C',
  273. 'SQLCHAR' => 'C',
  274. 'SQLDTIME' => 'T',
  275. 'SQLINTERVAL' => 'N',
  276. 'SQLBYTES' => 'B',
  277. 'SQLTEXT' => 'X',
  278. ## informix 10
  279. "SQLINT8" => 'I8',
  280. "SQLSERIAL8" => 'I8',
  281. "SQLNCHAR" => 'C',
  282. "SQLNVCHAR" => 'C',
  283. "SQLLVARCHAR" => 'X',
  284. "SQLBOOL" => 'L'
  285. );
  286. if (!$this->connection->IsConnected()) {
  287. $t = strtoupper($t);
  288. if (isset($typeMap[$t])) return $typeMap[$t];
  289. return 'N';
  290. }
  291. return $this->connection->MetaType($t,$len,$fieldobj);
  292. }
  293. function NameQuote($name = NULL,$allowBrackets=false)
  294. {
  295. if (!is_string($name)) {
  296. return FALSE;
  297. }
  298. $name = trim($name);
  299. if ( !is_object($this->connection) ) {
  300. return $name;
  301. }
  302. $quote = $this->connection->nameQuote;
  303. // if name is of the form `name`, quote it
  304. if ( preg_match('/^`(.+)`$/', $name, $matches) ) {
  305. return $quote . $matches[1] . $quote;
  306. }
  307. // if name contains special characters, quote it
  308. $regex = ($allowBrackets) ? $this->nameRegexBrackets : $this->nameRegex;
  309. if ( !preg_match('/^[' . $regex . ']+$/', $name) ) {
  310. return $quote . $name . $quote;
  311. }
  312. return $name;
  313. }
  314. function TableName($name)
  315. {
  316. if ( $this->schema ) {
  317. return $this->NameQuote($this->schema) .'.'. $this->NameQuote($name);
  318. }
  319. return $this->NameQuote($name);
  320. }
  321. // Executes the sql array returned by GetTableSQL and GetIndexSQL
  322. function ExecuteSQLArray($sql, $continueOnError = true)
  323. {
  324. $rez = 2;
  325. $conn = &$this->connection;
  326. $saved = $conn->debug;
  327. foreach($sql as $line) {
  328. if ($this->debug) $conn->debug = true;
  329. $ok = $conn->Execute($line);
  330. $conn->debug = $saved;
  331. if (!$ok) {
  332. if ($this->debug) ADOConnection::outp($conn->ErrorMsg());
  333. if (!$continueOnError) return 0;
  334. $rez = 1;
  335. }
  336. }
  337. return $rez;
  338. }
  339. /**
  340. Returns the actual type given a character code.
  341. C: varchar
  342. X: CLOB (character large object) or largest varchar size if CLOB is not supported
  343. C2: Multibyte varchar
  344. X2: Multibyte CLOB
  345. B: BLOB (binary large object)
  346. D: Date
  347. T: Date-time
  348. L: Integer field suitable for storing booleans (0 or 1)
  349. I: Integer
  350. F: Floating point number
  351. N: Numeric or decimal number
  352. */
  353. function ActualType($meta)
  354. {
  355. return $meta;
  356. }
  357. function CreateDatabase($dbname,$options=false)
  358. {
  359. $options = $this->_Options($options);
  360. $sql = array();
  361. $s = 'CREATE DATABASE ' . $this->NameQuote($dbname);
  362. if (isset($options[$this->upperName]))
  363. $s .= ' '.$options[$this->upperName];
  364. $sql[] = $s;
  365. return $sql;
  366. }
  367. /*
  368. Generates the SQL to create index. Returns an array of sql strings.
  369. */
  370. function CreateIndexSQL($idxname, $tabname, $flds, $idxoptions = false)
  371. {
  372. if (!is_array($flds)) {
  373. $flds = explode(',',$flds);
  374. }
  375. foreach($flds as $key => $fld) {
  376. # some indexes can use partial fields, eg. index first 32 chars of "name" with NAME(32)
  377. $flds[$key] = $this->NameQuote($fld,$allowBrackets=true);
  378. }
  379. return $this->_IndexSQL($this->NameQuote($idxname), $this->TableName($tabname), $flds, $this->_Options($idxoptions));
  380. }
  381. function DropIndexSQL ($idxname, $tabname = NULL)
  382. {
  383. return array(sprintf($this->dropIndex, $this->NameQuote($idxname), $this->TableName($tabname)));
  384. }
  385. function SetSchema($schema)
  386. {
  387. $this->schema = $schema;
  388. }
  389. function AddColumnSQL($tabname, $flds)
  390. {
  391. $tabname = $this->TableName ($tabname);
  392. $sql = array();
  393. list($lines,$pkey,$idxs) = $this->_GenFields($flds);
  394. // genfields can return FALSE at times
  395. if ($lines == null) $lines = array();
  396. $alter = 'ALTER TABLE ' . $tabname . $this->addCol . ' ';
  397. foreach($lines as $v) {
  398. $sql[] = $alter . $v;
  399. }
  400. if (is_array($idxs)) {
  401. foreach($idxs as $idx => $idxdef) {
  402. $sql_idxs = $this->CreateIndexSql($idx, $tabname, $idxdef['cols'], $idxdef['opts']);
  403. $sql = array_merge($sql, $sql_idxs);
  404. }
  405. }
  406. return $sql;
  407. }
  408. /**
  409. * Change the definition of one column
  410. *
  411. * As some DBM's can't do that on there own, you need to supply the complete defintion of the new table,
  412. * to allow, recreating the table and copying the content over to the new table
  413. * @param string $tabname table-name
  414. * @param string $flds column-name and type for the changed column
  415. * @param string $tableflds='' complete defintion of the new table, eg. for postgres, default ''
  416. * @param array/string $tableoptions='' options for the new table see CreateTableSQL, default ''
  417. * @return array with SQL strings
  418. */
  419. function AlterColumnSQL($tabname, $flds, $tableflds='',$tableoptions='')
  420. {
  421. $tabname = $this->TableName ($tabname);
  422. $sql = array();
  423. list($lines,$pkey,$idxs) = $this->_GenFields($flds);
  424. // genfields can return FALSE at times
  425. if ($lines == null) $lines = array();
  426. $alter = 'ALTER TABLE ' . $tabname . $this->alterCol . ' ';
  427. foreach($lines as $v) {
  428. $sql[] = $alter . $v;
  429. }
  430. if (is_array($idxs)) {
  431. foreach($idxs as $idx => $idxdef) {
  432. $sql_idxs = $this->CreateIndexSql($idx, $tabname, $idxdef['cols'], $idxdef['opts']);
  433. $sql = array_merge($sql, $sql_idxs);
  434. }
  435. }
  436. return $sql;
  437. }
  438. /**
  439. * Rename one column
  440. *
  441. * Some DBM's can only do this together with changeing the type of the column (even if that stays the same, eg. mysql)
  442. * @param string $tabname table-name
  443. * @param string $oldcolumn column-name to be renamed
  444. * @param string $newcolumn new column-name
  445. * @param string $flds='' complete column-defintion-string like for AddColumnSQL, only used by mysql atm., default=''
  446. * @return array with SQL strings
  447. */
  448. function RenameColumnSQL($tabname,$oldcolumn,$newcolumn,$flds='')
  449. {
  450. $tabname = $this->TableName ($tabname);
  451. if ($flds) {
  452. list($lines,$pkey,$idxs) = $this->_GenFields($flds);
  453. // genfields can return FALSE at times
  454. if ($lines == null) $lines = array();
  455. list(,$first) = each($lines);
  456. list(,$column_def) = split("[\t ]+",$first,2);
  457. }
  458. return array(sprintf($this->renameColumn,$tabname,$this->NameQuote($oldcolumn),$this->NameQuote($newcolumn),$column_def));
  459. }
  460. /**
  461. * Drop one column
  462. *
  463. * Some DBM's can't do that on there own, you need to supply the complete defintion of the new table,
  464. * to allow, recreating the table and copying the content over to the new table
  465. * @param string $tabname table-name
  466. * @param string $flds column-name and type for the changed column
  467. * @param string $tableflds='' complete defintion of the new table, eg. for postgres, default ''
  468. * @param array/string $tableoptions='' options for the new table see CreateTableSQL, default ''
  469. * @return array with SQL strings
  470. */
  471. function DropColumnSQL($tabname, $flds, $tableflds='',$tableoptions='')
  472. {
  473. $tabname = $this->TableName ($tabname);
  474. if (!is_array($flds)) $flds = explode(',',$flds);
  475. $sql = array();
  476. $alter = 'ALTER TABLE ' . $tabname . $this->dropCol . ' ';
  477. foreach($flds as $v) {
  478. $sql[] = $alter . $this->NameQuote($v);
  479. }
  480. return $sql;
  481. }
  482. function DropTableSQL($tabname)
  483. {
  484. return array (sprintf($this->dropTable, $this->TableName($tabname)));
  485. }
  486. function RenameTableSQL($tabname,$newname)
  487. {
  488. return array (sprintf($this->renameTable, $this->TableName($tabname),$this->TableName($newname)));
  489. }
  490. /**
  491. Generate the SQL to create table. Returns an array of sql strings.
  492. */
  493. function CreateTableSQL($tabname, $flds, $tableoptions=array())
  494. {
  495. list($lines,$pkey,$idxs) = $this->_GenFields($flds, true);
  496. // genfields can return FALSE at times
  497. if ($lines == null) $lines = array();
  498. $taboptions = $this->_Options($tableoptions);
  499. $tabname = $this->TableName ($tabname);
  500. $sql = $this->_TableSQL($tabname,$lines,$pkey,$taboptions);
  501. // ggiunta - 2006/10/12 - KLUDGE:
  502. // if we are on autoincrement, and table options includes REPLACE, the
  503. // autoincrement sequence has already been dropped on table creation sql, so
  504. // we avoid passing REPLACE to trigger creation code. This prevents
  505. // creating sql that double-drops the sequence
  506. if ($this->autoIncrement && isset($taboptions['REPLACE']))
  507. unset($taboptions['REPLACE']);
  508. $tsql = $this->_Triggers($tabname,$taboptions);
  509. foreach($tsql as $s) $sql[] = $s;
  510. if (is_array($idxs)) {
  511. foreach($idxs as $idx => $idxdef) {
  512. $sql_idxs = $this->CreateIndexSql($idx, $tabname, $idxdef['cols'], $idxdef['opts']);
  513. $sql = array_merge($sql, $sql_idxs);
  514. }
  515. }
  516. return $sql;
  517. }
  518. function _GenFields($flds,$widespacing=false)
  519. {
  520. if (is_string($flds)) {
  521. $padding = ' ';
  522. $txt = $flds.$padding;
  523. $flds = array();
  524. $flds0 = Lens_ParseArgs($txt,',');
  525. $hasparam = false;
  526. foreach($flds0 as $f0) {
  527. $f1 = array();
  528. foreach($f0 as $token) {
  529. switch (strtoupper($token)) {
  530. case 'INDEX':
  531. $f1['INDEX'] = '';
  532. // fall through intentionally
  533. case 'CONSTRAINT':
  534. case 'DEFAULT':
  535. $hasparam = $token;
  536. break;
  537. default:
  538. if ($hasparam) $f1[$hasparam] = $token;
  539. else $f1[] = $token;
  540. $hasparam = false;
  541. break;
  542. }
  543. }
  544. // 'index' token without a name means single column index: name it after column
  545. if (array_key_exists('INDEX', $f1) && $f1['INDEX'] == '') {
  546. $f1['INDEX'] = isset($f0['NAME']) ? $f0['NAME'] : $f0[0];
  547. // check if column name used to create an index name was quoted
  548. if (($f1['INDEX'][0] == '"' || $f1['INDEX'][0] == "'" || $f1['INDEX'][0] == "`") &&
  549. ($f1['INDEX'][0] == substr($f1['INDEX'], -1))) {
  550. $f1['INDEX'] = $f1['INDEX'][0].'idx_'.substr($f1['INDEX'], 1, -1).$f1['INDEX'][0];
  551. }
  552. else
  553. $f1['INDEX'] = 'idx_'.$f1['INDEX'];
  554. }
  555. // reset it, so we don't get next field 1st token as INDEX...
  556. $hasparam = false;
  557. $flds[] = $f1;
  558. }
  559. }
  560. $this->autoIncrement = false;
  561. $lines = array();
  562. $pkey = array();
  563. $idxs = array();
  564. foreach($flds as $fld) {
  565. $fld = _array_change_key_case($fld);
  566. $fname = false;
  567. $fdefault = false;
  568. $fautoinc = false;
  569. $ftype = false;
  570. $fsize = false;
  571. $fprec = false;
  572. $fprimary = false;
  573. $fnoquote = false;
  574. $fdefts = false;
  575. $fdefdate = false;
  576. $fconstraint = false;
  577. $fnotnull = false;
  578. $funsigned = false;
  579. $findex = '';
  580. $funiqueindex = false;
  581. //-----------------
  582. // Parse attributes
  583. foreach($fld as $attr => $v) {
  584. if ($attr == 2 && is_numeric($v)) $attr = 'SIZE';
  585. else if (is_numeric($attr) && $attr > 1 && !is_numeric($v)) $attr = strtoupper($v);
  586. switch($attr) {
  587. case '0':
  588. case 'NAME': $fname = $v; break;
  589. case '1':
  590. case 'TYPE': $ty = $v; $ftype = $this->ActualType(strtoupper($v)); break;
  591. case 'SIZE':
  592. $dotat = strpos($v,'.'); if ($dotat === false) $dotat = strpos($v,',');
  593. if ($dotat === false) $fsize = $v;
  594. else {
  595. $fsize = substr($v,0,$dotat);
  596. $fprec = substr($v,$dotat+1);
  597. }
  598. break;
  599. case 'UNSIGNED': $funsigned = true; break;
  600. case 'AUTOINCREMENT':
  601. case 'AUTO': $fautoinc = true; $fnotnull = true; break;
  602. case 'KEY':
  603. // a primary key col can be non unique in itself (if key spans many cols...)
  604. case 'PRIMARY': $fprimary = $v; $fnotnull = true; /*$funiqueindex = true;*/ break;
  605. case 'DEF':
  606. case 'DEFAULT': $fdefault = $v; break;
  607. case 'NOTNULL': $fnotnull = $v; break;
  608. case 'NOQUOTE': $fnoquote = $v; break;
  609. case 'DEFDATE': $fdefdate = $v; break;
  610. case 'DEFTIMESTAMP': $fdefts = $v; break;
  611. case 'CONSTRAINT': $fconstraint = $v; break;
  612. // let INDEX keyword create a 'very standard' index on column
  613. case 'INDEX': $findex = $v; break;
  614. case 'UNIQUE': $funiqueindex = true; break;
  615. } //switch
  616. } // foreach $fld
  617. //--------------------
  618. // VALIDATE FIELD INFO
  619. if (!strlen($fname)) {
  620. if ($this->debug) ADOConnection::outp("Undefined NAME");
  621. return false;
  622. }
  623. $fid = strtoupper(preg_replace('/^`(.+)`$/', '$1', $fname));
  624. $fname = $this->NameQuote($fname);
  625. if (!strlen($ftype)) {
  626. if ($this->debug) ADOConnection::outp("Undefined TYPE for field '$fname'");
  627. return false;
  628. } else {
  629. $ftype = strtoupper($ftype);
  630. }
  631. $ftype = $this->_GetSize($ftype, $ty, $fsize, $fprec);
  632. if ($ty == 'X' || $ty == 'X2' || $ty == 'B') $fnotnull = false; // some blob types do not accept nulls
  633. if ($fprimary) $pkey[] = $fname;
  634. // some databases do not allow blobs to have defaults
  635. if ($ty == 'X') $fdefault = false;
  636. // build list of indexes
  637. if ($findex != '') {
  638. if (array_key_exists($findex, $idxs)) {
  639. $idxs[$findex]['cols'][] = ($fname);
  640. if (in_array('UNIQUE', $idxs[$findex]['opts']) != $funiqueindex) {
  641. if ($this->debug) ADOConnection::outp("Index $findex defined once UNIQUE and once not");
  642. }
  643. if ($funiqueindex && !in_array('UNIQUE', $idxs[$findex]['opts']))
  644. $idxs[$findex]['opts'][] = 'UNIQUE';
  645. }
  646. else
  647. {
  648. $idxs[$findex] = array();
  649. $idxs[$findex]['cols'] = array($fname);
  650. if ($funiqueindex)
  651. $idxs[$findex]['opts'] = array('UNIQUE');
  652. else
  653. $idxs[$findex]['opts'] = array();
  654. }
  655. }
  656. //--------------------
  657. // CONSTRUCT FIELD SQL
  658. if ($fdefts) {
  659. if (substr($this->connection->databaseType,0,5) == 'mysql') {
  660. $ftype = 'TIMESTAMP';
  661. } else {
  662. $fdefault = $this->connection->sysTimeStamp;
  663. }
  664. } else if ($fdefdate) {
  665. if (substr($this->connection->databaseType,0,5) == 'mysql') {
  666. $ftype = 'TIMESTAMP';
  667. } else {
  668. $fdefault = $this->connection->sysDate;
  669. }
  670. } else if ($fdefault !== false && !$fnoquote) {
  671. if ($ty == 'C' or $ty == 'X' or
  672. ( substr($fdefault,0,1) != "'" && !is_numeric($fdefault))) {
  673. if (($ty == 'D' || $ty == 'T') && strtolower($fdefault) != 'null') {
  674. // convert default date into database-aware code
  675. if ($ty == 'T')
  676. {
  677. $fdefault = $this->connection->DBTimeStamp($fdefault);
  678. }
  679. else
  680. {
  681. $fdefault = $this->connection->DBDate($fdefault);
  682. }
  683. }
  684. else
  685. if (strlen($fdefault) != 1 && substr($fdefault,0,1) == ' ' && substr($fdefault,strlen($fdefault)-1) == ' ')
  686. $fdefault = trim($fdefault);
  687. else if (strtolower($fdefault) != 'null')
  688. $fdefault = $this->connection->qstr($fdefault);
  689. }
  690. }
  691. $suffix = $this->_CreateSuffix($fname,$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint,$funsigned);
  692. // add index creation
  693. if ($widespacing) $fname = str_pad($fname,24);
  694. // check for field names appearing twice
  695. if (array_key_exists($fid, $lines)) {
  696. ADOConnection::outp("Field '$fname' defined twice");
  697. }
  698. $lines[$fid] = $fname.' '.$ftype.$suffix;
  699. if ($fautoinc) $this->autoIncrement = true;
  700. } // foreach $flds
  701. return array($lines,$pkey,$idxs);
  702. }
  703. /**
  704. GENERATE THE SIZE PART OF THE DATATYPE
  705. $ftype is the actual type
  706. $ty is the type defined originally in the DDL
  707. */
  708. function _GetSize($ftype, $ty, $fsize, $fprec)
  709. {
  710. if (strlen($fsize) && $ty != 'X' && $ty != 'B' && strpos($ftype,'(') === false) {
  711. $ftype .= "(".$fsize;
  712. if (strlen($fprec)) $ftype .= ",".$fprec;
  713. $ftype .= ')';
  714. }
  715. return $ftype;
  716. }
  717. // return string must begin with space
  718. function _CreateSuffix($fname,$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint)
  719. {
  720. $suffix = '';
  721. if (strlen($fdefault)) $suffix .= " DEFAULT $fdefault";
  722. if ($fnotnull) $suffix .= ' NOT NULL';
  723. if ($fconstraint) $suffix .= ' '.$fconstraint;
  724. return $suffix;
  725. }
  726. function _IndexSQL($idxname, $tabname, $flds, $idxoptions)
  727. {
  728. $sql = array();
  729. if ( isset($idxoptions['REPLACE']) || isset($idxoptions['DROP']) ) {
  730. $sql[] = sprintf ($this->dropIndex, $idxname);
  731. if ( isset($idxoptions['DROP']) )
  732. return $sql;
  733. }
  734. if ( empty ($flds) ) {
  735. return $sql;
  736. }
  737. $unique = isset($idxoptions['UNIQUE']) ? ' UNIQUE' : '';
  738. $s = 'CREATE' . $unique . ' INDEX ' . $idxname . ' ON ' . $tabname . ' ';
  739. if ( isset($idxoptions[$this->upperName]) )
  740. $s .= $idxoptions[$this->upperName];
  741. if ( is_array($flds) )
  742. $flds = implode(', ',$flds);
  743. $s .= '(' . $flds . ')';
  744. $sql[] = $s;
  745. return $sql;
  746. }
  747. function _DropAutoIncrement($tabname)
  748. {
  749. return false;
  750. }
  751. function _TableSQL($tabname,$lines,$pkey,$tableoptions)
  752. {
  753. $sql = array();
  754. if (isset($tableoptions['REPLACE']) || isset ($tableoptions['DROP'])) {
  755. $sql[] = sprintf($this->dropTable,$tabname);
  756. if ($this->autoIncrement) {
  757. $sInc = $this->_DropAutoIncrement($tabname);
  758. if ($sInc) $sql[] = $sInc;
  759. }
  760. if ( isset ($tableoptions['DROP']) ) {
  761. return $sql;
  762. }
  763. }
  764. $s = "CREATE TABLE $tabname (\n";
  765. $s .= implode(",\n", $lines);
  766. if (sizeof($pkey)>0) {
  767. $s .= ",\n PRIMARY KEY (";
  768. $s .= implode(", ",$pkey).")";
  769. }
  770. if (isset($tableoptions['CONSTRAINTS']))
  771. $s .= "\n".$tableoptions['CONSTRAINTS'];
  772. if (isset($tableoptions[$this->upperName.'_CONSTRAINTS']))
  773. $s .= "\n".$tableoptions[$this->upperName.'_CONSTRAINTS'];
  774. $s .= "\n)";
  775. if (isset($tableoptions[$this->upperName])) $s .= $tableoptions[$this->upperName];
  776. $sql[] = $s;
  777. return $sql;
  778. }
  779. /**
  780. GENERATE TRIGGERS IF NEEDED
  781. used when table has auto-incrementing field that is emulated using triggers
  782. */
  783. function _Triggers($tabname,$taboptions)
  784. {
  785. return array();
  786. }
  787. /**
  788. Sanitize options, so that array elements with no keys are promoted to keys
  789. */
  790. function _Options($opts)
  791. {
  792. if (!is_array($opts)) return array();
  793. $newopts = array();
  794. foreach($opts as $k => $v) {
  795. if (is_numeric($k)) $newopts[strtoupper($v)] = $v;
  796. else $newopts[strtoupper($k)] = $v;
  797. }
  798. return $newopts;
  799. }
  800. /**
  801. "Florian Buzin [ easywe ]" <florian.buzin#easywe.de>
  802. This function changes/adds new fields to your table. You don't
  803. have to know if the col is new or not. It will check on its own.
  804. */
  805. function ChangeTableSQL($tablename, $flds, $tableoptions = false)
  806. {
  807. global $ADODB_FETCH_MODE;
  808. $save = $ADODB_FETCH_MODE;
  809. $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
  810. if ($this->connection->fetchMode !== false) $savem = $this->connection->SetFetchMode(false);
  811. // check table exists
  812. $save_handler = $this->connection->raiseErrorFn;
  813. $this->connection->raiseErrorFn = '';
  814. $cols = $this->MetaColumns($tablename);
  815. $this->connection->raiseErrorFn = $save_handler;
  816. if (isset($savem)) $this->connection->SetFetchMode($savem);
  817. $ADODB_FETCH_MODE = $save;
  818. if ( empty($cols)) {
  819. return $this->CreateTableSQL($tablename, $flds, $tableoptions);
  820. }
  821. if (is_array($flds)) {
  822. // Cycle through the update fields, comparing
  823. // existing fields to fields to update.
  824. // if the Metatype and size is exactly the
  825. // same, ignore - by Mark Newham
  826. $holdflds = array();
  827. foreach($flds as $k=>$v) {
  828. if ( isset($cols[$k]) && is_object($cols[$k]) ) {
  829. // If already not allowing nulls, then don't change
  830. $obj = $cols[$k];
  831. if (isset($obj->not_null) && $obj->not_null)
  832. $v = str_replace('NOT NULL','',$v);
  833. $c = $cols[$k];
  834. $ml = $c->max_length;
  835. $mt = $this->MetaType($c->type,$ml);
  836. if ($ml == -1) $ml = '';
  837. if ($mt == 'X') $ml = $v['SIZE'];
  838. if (($mt != $v['TYPE']) || $ml != $v['SIZE']) {
  839. $holdflds[$k] = $v;
  840. }
  841. } else {
  842. $holdflds[$k] = $v;
  843. }
  844. }
  845. $flds = $holdflds;
  846. }
  847. // already exists, alter table instead
  848. list($lines,$pkey,$idxs) = $this->_GenFields($flds);
  849. // genfields can return FALSE at times
  850. if ($lines == null) $lines = array();
  851. $alter = 'ALTER TABLE ' . $this->TableName($tablename);
  852. $sql = array();
  853. foreach ( $lines as $id => $v ) {
  854. if ( isset($cols[$id]) && is_object($cols[$id]) ) {
  855. $flds = Lens_ParseArgs($v,',');
  856. // We are trying to change the size of the field, if not allowed, simply ignore the request.
  857. // $flds[1] holds the type, $flds[2] holds the size -postnuke addition
  858. if ($flds && in_array(strtoupper(substr($flds[0][1],0,4)),$this->invalidResizeTypes4)
  859. && (isset($flds[0][2]) && is_numeric($flds[0][2]))) {
  860. if ($this->debug) ADOConnection::outp(sprintf("<h3>%s cannot be changed to %s currently</h3>", $flds[0][0], $flds[0][1]));
  861. #echo "<h3>$this->alterCol cannot be changed to $flds currently</h3>";
  862. continue;
  863. }
  864. $sql[] = $alter . $this->alterCol . ' ' . $v;
  865. } else {
  866. $sql[] = $alter . $this->addCol . ' ' . $v;
  867. }
  868. }
  869. return $sql;
  870. }
  871. } // class
  872. ?>