PageRenderTime 47ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/rdfapi-php/api/util/adodb/adodb-datadict.inc.php

https://github.com/komagata/plnet
PHP | 674 lines | 589 code | 35 blank | 50 comment | 49 complexity | b915b4487a80c5bbfa441b7f11a19aaa MD5 | raw file
Possible License(s): LGPL-2.1
  1. <?php
  2. /**
  3. V4.52 10 Aug 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). 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";
  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. while ($pos < $max) {
  52. $ch = substr($args,$pos,1);
  53. switch($ch) {
  54. case ' ':
  55. case "\t":
  56. case "\n":
  57. case "\r":
  58. if (!$quoted) {
  59. if ($intoken) {
  60. $intoken = false;
  61. $tokens[$stmtno][] = implode('',$tokarr);
  62. }
  63. break;
  64. }
  65. $tokarr[] = $ch;
  66. break;
  67. case '`':
  68. if ($intoken) $tokarr[] = $ch;
  69. case '(':
  70. case ')':
  71. case '"':
  72. case "'":
  73. if ($intoken) {
  74. if (empty($endquote)) {
  75. $tokens[$stmtno][] = implode('',$tokarr);
  76. if ($ch == '(') $endquote = ')';
  77. else $endquote = $ch;
  78. $quoted = true;
  79. $intoken = true;
  80. $tokarr = array();
  81. } else if ($endquote == $ch) {
  82. $ch2 = substr($args,$pos+1,1);
  83. if ($ch2 == $endquote) {
  84. $pos += 1;
  85. $tokarr[] = $ch2;
  86. } else {
  87. $quoted = false;
  88. $intoken = false;
  89. $tokens[$stmtno][] = implode('',$tokarr);
  90. $endquote = '';
  91. }
  92. } else
  93. $tokarr[] = $ch;
  94. }else {
  95. if ($ch == '(') $endquote = ')';
  96. else $endquote = $ch;
  97. $quoted = true;
  98. $intoken = true;
  99. $tokarr = array();
  100. if ($ch == '`') $tokarr[] = '`';
  101. }
  102. break;
  103. default:
  104. if (!$intoken) {
  105. if ($ch == $endstmtchar) {
  106. $stmtno += 1;
  107. $tokens[$stmtno] = array();
  108. break;
  109. }
  110. $intoken = true;
  111. $quoted = false;
  112. $endquote = false;
  113. $tokarr = array();
  114. }
  115. if ($quoted) $tokarr[] = $ch;
  116. else if (ctype_alnum($ch) || strpos($tokenchars,$ch) !== false) $tokarr[] = $ch;
  117. else {
  118. if ($ch == $endstmtchar) {
  119. $tokens[$stmtno][] = implode('',$tokarr);
  120. $stmtno += 1;
  121. $tokens[$stmtno] = array();
  122. $intoken = false;
  123. $tokarr = array();
  124. break;
  125. }
  126. $tokens[$stmtno][] = implode('',$tokarr);
  127. $tokens[$stmtno][] = $ch;
  128. $intoken = false;
  129. }
  130. }
  131. $pos += 1;
  132. }
  133. return $tokens;
  134. }
  135. class ADODB_DataDict {
  136. var $connection;
  137. var $debug = false;
  138. var $dropTable = 'DROP TABLE %s';
  139. var $dropIndex = 'DROP INDEX %s';
  140. var $addCol = ' ADD';
  141. var $alterCol = ' ALTER COLUMN';
  142. var $dropCol = ' DROP COLUMN';
  143. var $nameRegex = '\w';
  144. var $schema = false;
  145. var $serverInfo = array();
  146. var $autoIncrement = false;
  147. var $dataProvider;
  148. var $blobSize = 100; /// any varchar/char field this size or greater is treated as a blob
  149. /// in other words, we use a text area for editting.
  150. function GetCommentSQL($table,$col)
  151. {
  152. return false;
  153. }
  154. function SetCommentSQL($table,$col,$cmt)
  155. {
  156. return false;
  157. }
  158. function &MetaTables()
  159. {
  160. return $this->connection->MetaTables();
  161. }
  162. function &MetaColumns($tab, $upper=true, $schema=false)
  163. {
  164. return $this->connection->MetaColumns($this->TableName($tab), $upper, $schema);
  165. }
  166. function &MetaPrimaryKeys($tab,$owner=false,$intkey=false)
  167. {
  168. return $this->connection->MetaPrimaryKeys($this->TableName($tab), $owner, $intkey);
  169. }
  170. function &MetaIndexes($table, $primary = false, $owner = false)
  171. {
  172. return $this->connection->MetaIndexes($this->TableName($table), $primary, $owner);
  173. }
  174. function MetaType($t,$len=-1,$fieldobj=false)
  175. {
  176. return ADORecordSet::MetaType($t,$len,$fieldobj);
  177. }
  178. function NameQuote($name = NULL)
  179. {
  180. if (!is_string($name)) {
  181. return FALSE;
  182. }
  183. $name = trim($name);
  184. if ( !is_object($this->connection) ) {
  185. return $name;
  186. }
  187. $quote = $this->connection->nameQuote;
  188. // if name is of the form `name`, quote it
  189. if ( preg_match('/^`(.+)`$/', $name, $matches) ) {
  190. return $quote . $matches[1] . $quote;
  191. }
  192. // if name contains special characters, quote it
  193. if ( !preg_match('/^[' . $this->nameRegex . ']+$/', $name) ) {
  194. return $quote . $name . $quote;
  195. }
  196. return $name;
  197. }
  198. function TableName($name)
  199. {
  200. if ( $this->schema ) {
  201. return $this->NameQuote($this->schema) .'.'. $this->NameQuote($name);
  202. }
  203. return $this->NameQuote($name);
  204. }
  205. // Executes the sql array returned by GetTableSQL and GetIndexSQL
  206. function ExecuteSQLArray($sql, $continueOnError = true)
  207. {
  208. $rez = 2;
  209. $conn = &$this->connection;
  210. $saved = $conn->debug;
  211. foreach($sql as $line) {
  212. if ($this->debug) $conn->debug = true;
  213. $ok = $conn->Execute($line);
  214. $conn->debug = $saved;
  215. if (!$ok) {
  216. if ($this->debug) ADOConnection::outp($conn->ErrorMsg());
  217. if (!$continueOnError) return 0;
  218. $rez = 1;
  219. }
  220. }
  221. return $rez;
  222. }
  223. /*
  224. Returns the actual type given a character code.
  225. C: varchar
  226. X: CLOB (character large object) or largest varchar size if CLOB is not supported
  227. C2: Multibyte varchar
  228. X2: Multibyte CLOB
  229. B: BLOB (binary large object)
  230. D: Date
  231. T: Date-time
  232. L: Integer field suitable for storing booleans (0 or 1)
  233. I: Integer
  234. F: Floating point number
  235. N: Numeric or decimal number
  236. */
  237. function ActualType($meta)
  238. {
  239. return $meta;
  240. }
  241. function CreateDatabase($dbname,$options=false)
  242. {
  243. $options = $this->_Options($options);
  244. $sql = array();
  245. $s = 'CREATE DATABASE ' . $this->NameQuote($dbname);
  246. if (isset($options[$this->upperName]))
  247. $s .= ' '.$options[$this->upperName];
  248. $sql[] = $s;
  249. return $sql;
  250. }
  251. /*
  252. Generates the SQL to create index. Returns an array of sql strings.
  253. */
  254. function CreateIndexSQL($idxname, $tabname, $flds, $idxoptions = false)
  255. {
  256. if (!is_array($flds)) {
  257. $flds = explode(',',$flds);
  258. }
  259. foreach($flds as $key => $fld) {
  260. $flds[$key] = $this->NameQuote($fld);
  261. }
  262. return $this->_IndexSQL($this->NameQuote($idxname), $this->TableName($tabname), $flds, $this->_Options($idxoptions));
  263. }
  264. function DropIndexSQL ($idxname, $tabname = NULL)
  265. {
  266. return array(sprintf($this->dropIndex, $this->NameQuote($idxname), $this->TableName($tabname)));
  267. }
  268. function SetSchema($schema)
  269. {
  270. $this->schema = $schema;
  271. }
  272. function AddColumnSQL($tabname, $flds)
  273. {
  274. $tabname = $this->TableName ($tabname);
  275. $sql = array();
  276. list($lines,$pkey) = $this->_GenFields($flds);
  277. $alter = 'ALTER TABLE ' . $tabname . $this->addCol . ' ';
  278. foreach($lines as $v) {
  279. $sql[] = $alter . $v;
  280. }
  281. return $sql;
  282. }
  283. function AlterColumnSQL($tabname, $flds)
  284. {
  285. $tabname = $this->TableName ($tabname);
  286. $sql = array();
  287. list($lines,$pkey) = $this->_GenFields($flds);
  288. $alter = 'ALTER TABLE ' . $tabname . $this->alterCol . ' ';
  289. foreach($lines as $v) {
  290. $sql[] = $alter . $v;
  291. }
  292. return $sql;
  293. }
  294. function DropColumnSQL($tabname, $flds)
  295. {
  296. $tabname = $this->TableName ($tabname);
  297. if (!is_array($flds)) $flds = explode(',',$flds);
  298. $sql = array();
  299. $alter = 'ALTER TABLE ' . $tabname . $this->dropCol . ' ';
  300. foreach($flds as $v) {
  301. $sql[] = $alter . $this->NameQuote($v);
  302. }
  303. return $sql;
  304. }
  305. function DropTableSQL($tabname)
  306. {
  307. return array (sprintf($this->dropTable, $this->TableName($tabname)));
  308. }
  309. /*
  310. Generate the SQL to create table. Returns an array of sql strings.
  311. */
  312. function CreateTableSQL($tabname, $flds, $tableoptions=false)
  313. {
  314. if (!$tableoptions) $tableoptions = array();
  315. list($lines,$pkey) = $this->_GenFields($flds);
  316. $taboptions = $this->_Options($tableoptions);
  317. $tabname = $this->TableName ($tabname);
  318. $sql = $this->_TableSQL($tabname,$lines,$pkey,$taboptions);
  319. $tsql = $this->_Triggers($tabname,$taboptions);
  320. foreach($tsql as $s) $sql[] = $s;
  321. return $sql;
  322. }
  323. function _GenFields($flds)
  324. {
  325. if (is_string($flds)) {
  326. $padding = ' ';
  327. $txt = $flds.$padding;
  328. $flds = array();
  329. $flds0 = Lens_ParseArgs($txt,',');
  330. $hasparam = false;
  331. foreach($flds0 as $f0) {
  332. $f1 = array();
  333. foreach($f0 as $token) {
  334. switch (strtoupper($token)) {
  335. case 'CONSTRAINT':
  336. case 'DEFAULT':
  337. $hasparam = $token;
  338. break;
  339. default:
  340. if ($hasparam) $f1[$hasparam] = $token;
  341. else $f1[] = $token;
  342. $hasparam = false;
  343. break;
  344. }
  345. }
  346. $flds[] = $f1;
  347. }
  348. }
  349. $this->autoIncrement = false;
  350. $lines = array();
  351. $pkey = array();
  352. foreach($flds as $fld) {
  353. $fld = _array_change_key_case($fld);
  354. $fname = false;
  355. $fdefault = false;
  356. $fautoinc = false;
  357. $ftype = false;
  358. $fsize = false;
  359. $fprec = false;
  360. $fprimary = false;
  361. $fnoquote = false;
  362. $fdefts = false;
  363. $fdefdate = false;
  364. $fconstraint = false;
  365. $fnotnull = false;
  366. $funsigned = false;
  367. //-----------------
  368. // Parse attributes
  369. foreach($fld as $attr => $v) {
  370. if ($attr == 2 && is_numeric($v)) $attr = 'SIZE';
  371. else if (is_numeric($attr) && $attr > 1 && !is_numeric($v)) $attr = strtoupper($v);
  372. switch($attr) {
  373. case '0':
  374. case 'NAME': $fname = $v; break;
  375. case '1':
  376. case 'TYPE': $ty = $v; $ftype = $this->ActualType(strtoupper($v)); break;
  377. case 'SIZE':
  378. $dotat = strpos($v,'.'); if ($dotat === false) $dotat = strpos($v,',');
  379. if ($dotat === false) $fsize = $v;
  380. else {
  381. $fsize = substr($v,0,$dotat);
  382. $fprec = substr($v,$dotat+1);
  383. }
  384. break;
  385. case 'UNSIGNED': $funsigned = true; break;
  386. case 'AUTOINCREMENT':
  387. case 'AUTO': $fautoinc = true; $fnotnull = true; break;
  388. case 'KEY':
  389. case 'PRIMARY': $fprimary = $v; $fnotnull = true; break;
  390. case 'DEF':
  391. case 'DEFAULT': $fdefault = $v; break;
  392. case 'NOTNULL': $fnotnull = $v; break;
  393. case 'NOQUOTE': $fnoquote = $v; break;
  394. case 'DEFDATE': $fdefdate = $v; break;
  395. case 'DEFTIMESTAMP': $fdefts = $v; break;
  396. case 'CONSTRAINT': $fconstraint = $v; break;
  397. } //switch
  398. } // foreach $fld
  399. //--------------------
  400. // VALIDATE FIELD INFO
  401. if (!strlen($fname)) {
  402. if ($this->debug) ADOConnection::outp("Undefined NAME");
  403. return false;
  404. }
  405. $fid = strtoupper(preg_replace('/^`(.+)`$/', '$1', $fname));
  406. $fname = $this->NameQuote($fname);
  407. if (!strlen($ftype)) {
  408. if ($this->debug) ADOConnection::outp("Undefined TYPE for field '$fname'");
  409. return false;
  410. } else {
  411. $ftype = strtoupper($ftype);
  412. }
  413. $ftype = $this->_GetSize($ftype, $ty, $fsize, $fprec);
  414. if ($ty == 'X' || $ty == 'X2' || $ty == 'B') $fnotnull = false; // some blob types do not accept nulls
  415. if ($fprimary) $pkey[] = $fname;
  416. // some databases do not allow blobs to have defaults
  417. if ($ty == 'X') $fdefault = false;
  418. //--------------------
  419. // CONSTRUCT FIELD SQL
  420. if ($fdefts) {
  421. if (substr($this->connection->databaseType,0,5) == 'mysql') {
  422. $ftype = 'TIMESTAMP';
  423. } else {
  424. $fdefault = $this->connection->sysTimeStamp;
  425. }
  426. } else if ($fdefdate) {
  427. if (substr($this->connection->databaseType,0,5) == 'mysql') {
  428. $ftype = 'TIMESTAMP';
  429. } else {
  430. $fdefault = $this->connection->sysDate;
  431. }
  432. } else if (strlen($fdefault) && !$fnoquote)
  433. if ($ty == 'C' or $ty == 'X' or
  434. ( substr($fdefault,0,1) != "'" && !is_numeric($fdefault)))
  435. if (strlen($fdefault) != 1 && substr($fdefault,0,1) == ' ' && substr($fdefault,strlen($fdefault)-1) == ' ')
  436. $fdefault = trim($fdefault);
  437. else if (strtolower($fdefault) != 'null')
  438. $fdefault = $this->connection->qstr($fdefault);
  439. $suffix = $this->_CreateSuffix($fname,$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint,$funsigned);
  440. $fname = str_pad($fname,16);
  441. $lines[$fid] = $fname.' '.$ftype.$suffix;
  442. if ($fautoinc) $this->autoIncrement = true;
  443. } // foreach $flds
  444. return array($lines,$pkey);
  445. }
  446. /*
  447. GENERATE THE SIZE PART OF THE DATATYPE
  448. $ftype is the actual type
  449. $ty is the type defined originally in the DDL
  450. */
  451. function _GetSize($ftype, $ty, $fsize, $fprec)
  452. {
  453. if (strlen($fsize) && $ty != 'X' && $ty != 'B' && strpos($ftype,'(') === false) {
  454. $ftype .= "(".$fsize;
  455. if (strlen($fprec)) $ftype .= ",".$fprec;
  456. $ftype .= ')';
  457. }
  458. return $ftype;
  459. }
  460. // return string must begin with space
  461. function _CreateSuffix($fname,$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint)
  462. {
  463. $suffix = '';
  464. if (strlen($fdefault)) $suffix .= " DEFAULT $fdefault";
  465. if ($fnotnull) $suffix .= ' NOT NULL';
  466. if ($fconstraint) $suffix .= ' '.$fconstraint;
  467. return $suffix;
  468. }
  469. function _IndexSQL($idxname, $tabname, $flds, $idxoptions)
  470. {
  471. $sql = array();
  472. if ( isset($idxoptions['REPLACE']) || isset($idxoptions['DROP']) ) {
  473. $sql[] = sprintf ($this->dropIndex, $idxname);
  474. if ( isset($idxoptions['DROP']) )
  475. return $sql;
  476. }
  477. if ( empty ($flds) ) {
  478. return $sql;
  479. }
  480. $unique = isset($idxoptions['UNIQUE']) ? ' UNIQUE' : '';
  481. $s = 'CREATE' . $unique . ' INDEX ' . $idxname . ' ON ' . $tabname . ' ';
  482. if ( isset($idxoptions[$this->upperName]) )
  483. $s .= $idxoptions[$this->upperName];
  484. if ( is_array($flds) )
  485. $flds = implode(', ',$flds);
  486. $s .= '(' . $flds . ')';
  487. $sql[] = $s;
  488. return $sql;
  489. }
  490. function _DropAutoIncrement($tabname)
  491. {
  492. return false;
  493. }
  494. function _TableSQL($tabname,$lines,$pkey,$tableoptions)
  495. {
  496. $sql = array();
  497. if (isset($tableoptions['REPLACE']) || isset ($tableoptions['DROP'])) {
  498. $sql[] = sprintf($this->dropTable,$tabname);
  499. if ($this->autoIncrement) {
  500. $sInc = $this->_DropAutoIncrement($tabname);
  501. if ($sInc) $sql[] = $sInc;
  502. }
  503. if ( isset ($tableoptions['DROP']) ) {
  504. return $sql;
  505. }
  506. }
  507. $s = "CREATE TABLE $tabname (\n";
  508. $s .= implode(",\n", $lines);
  509. if (sizeof($pkey)>0) {
  510. $s .= ",\n PRIMARY KEY (";
  511. $s .= implode(", ",$pkey).")";
  512. }
  513. if (isset($tableoptions['CONSTRAINTS']))
  514. $s .= "\n".$tableoptions['CONSTRAINTS'];
  515. if (isset($tableoptions[$this->upperName.'_CONSTRAINTS']))
  516. $s .= "\n".$tableoptions[$this->upperName.'_CONSTRAINTS'];
  517. $s .= "\n)";
  518. if (isset($tableoptions[$this->upperName])) $s .= $tableoptions[$this->upperName];
  519. $sql[] = $s;
  520. return $sql;
  521. }
  522. /*
  523. GENERATE TRIGGERS IF NEEDED
  524. used when table has auto-incrementing field that is emulated using triggers
  525. */
  526. function _Triggers($tabname,$taboptions)
  527. {
  528. return array();
  529. }
  530. /*
  531. Sanitize options, so that array elements with no keys are promoted to keys
  532. */
  533. function _Options($opts)
  534. {
  535. if (!is_array($opts)) return array();
  536. $newopts = array();
  537. foreach($opts as $k => $v) {
  538. if (is_numeric($k)) $newopts[strtoupper($v)] = $v;
  539. else $newopts[strtoupper($k)] = $v;
  540. }
  541. return $newopts;
  542. }
  543. /*
  544. "Florian Buzin [ easywe ]" <florian.buzin@easywe.de>
  545. This function changes/adds new fields to your table. You don't
  546. have to know if the col is new or not. It will check on its own.
  547. */
  548. function ChangeTableSQL($tablename, $flds, $tableoptions = false)
  549. {
  550. // check table exists
  551. $cols = &$this->MetaColumns($tablename);
  552. if ( empty($cols)) {
  553. return $this->CreateTableSQL($tablename, $flds, $tableoptions);
  554. }
  555. // already exists, alter table instead
  556. list($lines,$pkey) = $this->_GenFields($flds);
  557. $alter = 'ALTER TABLE ' . $this->TableName($tablename);
  558. $sql = array();
  559. foreach ( $lines as $id => $v ) {
  560. if ( isset($cols[$id]) && is_object($cols[$id]) ) {
  561. $sql[] = $alter . $this->alterCol . ' ' . $v;
  562. } else {
  563. $sql[] = $alter . $this->addCol . ' ' . $v;
  564. }
  565. }
  566. return $sql;
  567. }
  568. } // class
  569. ?>