PageRenderTime 46ms CodeModel.GetById 18ms RepoModel.GetById 1ms app.codeStats 0ms

/include/adodb/adodb-xmlschema03.inc.php

https://github.com/radicaldesigns/amp
PHP | 2403 lines | 1197 code | 307 blank | 899 comment | 167 complexity | 617d3577c169e81e19d2119497d204f3 MD5 | raw file
Possible License(s): LGPL-2.1, GPL-2.0, BSD-3-Clause, LGPL-2.0, CC-BY-SA-3.0, AGPL-1.0

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. // Copyright (c) 2004-2005 ars Cognita Inc., all rights reserved
  3. /* ******************************************************************************
  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. *******************************************************************************/
  8. /**
  9. * xmlschema is a class that allows the user to quickly and easily
  10. * build a database on any ADOdb-supported platform using a simple
  11. * XML schema.
  12. *
  13. * Last Editor: $Author: jlim $
  14. * @author Richard Tango-Lowy & Dan Cech
  15. * @version $Revision: 1.62 $
  16. *
  17. * @package axmls
  18. * @tutorial getting_started.pkg
  19. */
  20. function _file_get_contents($file)
  21. {
  22. if (function_exists('file_get_contents')) return file_get_contents($file);
  23. $f = fopen($file,'r');
  24. if (!$f) return '';
  25. $t = '';
  26. while ($s = fread($f,100000)) $t .= $s;
  27. fclose($f);
  28. return $t;
  29. }
  30. /**
  31. * Debug on or off
  32. */
  33. if( !defined( 'XMLS_DEBUG' ) ) {
  34. define( 'XMLS_DEBUG', FALSE );
  35. }
  36. /**
  37. * Default prefix key
  38. */
  39. if( !defined( 'XMLS_PREFIX' ) ) {
  40. define( 'XMLS_PREFIX', '%%P' );
  41. }
  42. /**
  43. * Maximum length allowed for object prefix
  44. */
  45. if( !defined( 'XMLS_PREFIX_MAXLEN' ) ) {
  46. define( 'XMLS_PREFIX_MAXLEN', 10 );
  47. }
  48. /**
  49. * Execute SQL inline as it is generated
  50. */
  51. if( !defined( 'XMLS_EXECUTE_INLINE' ) ) {
  52. define( 'XMLS_EXECUTE_INLINE', FALSE );
  53. }
  54. /**
  55. * Continue SQL Execution if an error occurs?
  56. */
  57. if( !defined( 'XMLS_CONTINUE_ON_ERROR' ) ) {
  58. define( 'XMLS_CONTINUE_ON_ERROR', FALSE );
  59. }
  60. /**
  61. * Current Schema Version
  62. */
  63. if( !defined( 'XMLS_SCHEMA_VERSION' ) ) {
  64. define( 'XMLS_SCHEMA_VERSION', '0.3' );
  65. }
  66. /**
  67. * Default Schema Version. Used for Schemas without an explicit version set.
  68. */
  69. if( !defined( 'XMLS_DEFAULT_SCHEMA_VERSION' ) ) {
  70. define( 'XMLS_DEFAULT_SCHEMA_VERSION', '0.1' );
  71. }
  72. /**
  73. * How to handle data rows that already exist in a database during and upgrade.
  74. * Options are INSERT (attempts to insert duplicate rows), UPDATE (updates existing
  75. * rows) and IGNORE (ignores existing rows).
  76. */
  77. if( !defined( 'XMLS_MODE_INSERT' ) ) {
  78. define( 'XMLS_MODE_INSERT', 0 );
  79. }
  80. if( !defined( 'XMLS_MODE_UPDATE' ) ) {
  81. define( 'XMLS_MODE_UPDATE', 1 );
  82. }
  83. if( !defined( 'XMLS_MODE_IGNORE' ) ) {
  84. define( 'XMLS_MODE_IGNORE', 2 );
  85. }
  86. if( !defined( 'XMLS_EXISTING_DATA' ) ) {
  87. define( 'XMLS_EXISTING_DATA', XMLS_MODE_INSERT );
  88. }
  89. /**
  90. * Default Schema Version. Used for Schemas without an explicit version set.
  91. */
  92. if( !defined( 'XMLS_DEFAULT_UPGRADE_METHOD' ) ) {
  93. define( 'XMLS_DEFAULT_UPGRADE_METHOD', 'ALTER' );
  94. }
  95. /**
  96. * Include the main ADODB library
  97. */
  98. if( !defined( '_ADODB_LAYER' ) ) {
  99. require( 'adodb.inc.php' );
  100. require( 'adodb-datadict.inc.php' );
  101. }
  102. /**
  103. * Abstract DB Object. This class provides basic methods for database objects, such
  104. * as tables and indexes.
  105. *
  106. * @package axmls
  107. * @access private
  108. */
  109. class dbObject {
  110. /**
  111. * var object Parent
  112. */
  113. var $parent;
  114. /**
  115. * var string current element
  116. */
  117. var $currentElement;
  118. /**
  119. * NOP
  120. */
  121. function dbObject( &$parent, $attributes = NULL ) {
  122. $this->parent = $parent;
  123. }
  124. /**
  125. * XML Callback to process start elements
  126. *
  127. * @access private
  128. */
  129. function _tag_open( &$parser, $tag, $attributes ) {
  130. }
  131. /**
  132. * XML Callback to process CDATA elements
  133. *
  134. * @access private
  135. */
  136. function _tag_cdata( &$parser, $cdata ) {
  137. }
  138. /**
  139. * XML Callback to process end elements
  140. *
  141. * @access private
  142. */
  143. function _tag_close( &$parser, $tag ) {
  144. }
  145. function create() {
  146. return array();
  147. }
  148. /**
  149. * Destroys the object
  150. */
  151. function destroy() {
  152. unset( $this );
  153. }
  154. /**
  155. * Checks whether the specified RDBMS is supported by the current
  156. * database object or its ranking ancestor.
  157. *
  158. * @param string $platform RDBMS platform name (from ADODB platform list).
  159. * @return boolean TRUE if RDBMS is supported; otherwise returns FALSE.
  160. */
  161. function supportedPlatform( $platform = NULL ) {
  162. return is_object( $this->parent ) ? $this->parent->supportedPlatform( $platform ) : TRUE;
  163. }
  164. /**
  165. * Returns the prefix set by the ranking ancestor of the database object.
  166. *
  167. * @param string $name Prefix string.
  168. * @return string Prefix.
  169. */
  170. function prefix( $name = '' ) {
  171. return is_object( $this->parent ) ? $this->parent->prefix( $name ) : $name;
  172. }
  173. /**
  174. * Extracts a field ID from the specified field.
  175. *
  176. * @param string $field Field.
  177. * @return string Field ID.
  178. */
  179. function FieldID( $field ) {
  180. return strtoupper( preg_replace( '/^`(.+)`$/', '$1', $field ) );
  181. }
  182. }
  183. /**
  184. * Creates a table object in ADOdb's datadict format
  185. *
  186. * This class stores information about a database table. As charactaristics
  187. * of the table are loaded from the external source, methods and properties
  188. * of this class are used to build up the table description in ADOdb's
  189. * datadict format.
  190. *
  191. * @package axmls
  192. * @access private
  193. */
  194. class dbTable extends dbObject {
  195. /**
  196. * @var string Table name
  197. */
  198. var $name;
  199. /**
  200. * @var array Field specifier: Meta-information about each field
  201. */
  202. var $fields = array();
  203. /**
  204. * @var array List of table indexes.
  205. */
  206. var $indexes = array();
  207. /**
  208. * @var array Table options: Table-level options
  209. */
  210. var $opts = array();
  211. /**
  212. * @var string Field index: Keeps track of which field is currently being processed
  213. */
  214. var $current_field;
  215. /**
  216. * @var boolean Mark table for destruction
  217. * @access private
  218. */
  219. var $drop_table;
  220. /**
  221. * @var boolean Mark field for destruction (not yet implemented)
  222. * @access private
  223. */
  224. var $drop_field = array();
  225. /**
  226. * @var array Platform-specific options
  227. * @access private
  228. */
  229. var $currentPlatform = true;
  230. /**
  231. * Iniitializes a new table object.
  232. *
  233. * @param string $prefix DB Object prefix
  234. * @param array $attributes Array of table attributes.
  235. */
  236. function dbTable( &$parent, $attributes = NULL ) {
  237. $this->parent = $parent;
  238. $this->name = $this->prefix($attributes['NAME']);
  239. }
  240. /**
  241. * XML Callback to process start elements. Elements currently
  242. * processed are: INDEX, DROP, FIELD, KEY, NOTNULL, AUTOINCREMENT & DEFAULT.
  243. *
  244. * @access private
  245. */
  246. function _tag_open( &$parser, $tag, $attributes ) {
  247. $this->currentElement = strtoupper( $tag );
  248. switch( $this->currentElement ) {
  249. case 'INDEX':
  250. if( !isset( $attributes['PLATFORM'] ) OR $this->supportedPlatform( $attributes['PLATFORM'] ) ) {
  251. xml_set_object( $parser, $this->addIndex( $attributes ) );
  252. }
  253. break;
  254. case 'DATA':
  255. if( !isset( $attributes['PLATFORM'] ) OR $this->supportedPlatform( $attributes['PLATFORM'] ) ) {
  256. xml_set_object( $parser, $this->addData( $attributes ) );
  257. }
  258. break;
  259. case 'DROP':
  260. $this->drop();
  261. break;
  262. case 'FIELD':
  263. // Add a field
  264. $fieldName = $attributes['NAME'];
  265. $fieldType = $attributes['TYPE'];
  266. $fieldSize = isset( $attributes['SIZE'] ) ? $attributes['SIZE'] : NULL;
  267. $fieldOpts = !empty( $attributes['OPTS'] ) ? $attributes['OPTS'] : NULL;
  268. $this->addField( $fieldName, $fieldType, $fieldSize, $fieldOpts );
  269. break;
  270. case 'KEY':
  271. case 'NOTNULL':
  272. case 'AUTOINCREMENT':
  273. case 'DEFDATE':
  274. case 'DEFTIMESTAMP':
  275. case 'UNSIGNED':
  276. // Add a field option
  277. $this->addFieldOpt( $this->current_field, $this->currentElement );
  278. break;
  279. case 'DEFAULT':
  280. // Add a field option to the table object
  281. // Work around ADOdb datadict issue that misinterprets empty strings.
  282. if( $attributes['VALUE'] == '' ) {
  283. $attributes['VALUE'] = " '' ";
  284. }
  285. $this->addFieldOpt( $this->current_field, $this->currentElement, $attributes['VALUE'] );
  286. break;
  287. case 'OPT':
  288. case 'CONSTRAINT':
  289. // Accept platform-specific options
  290. $this->currentPlatform = ( !isset( $attributes['PLATFORM'] ) OR $this->supportedPlatform( $attributes['PLATFORM'] ) );
  291. break;
  292. default:
  293. // print_r( array( $tag, $attributes ) );
  294. }
  295. }
  296. /**
  297. * XML Callback to process CDATA elements
  298. *
  299. * @access private
  300. */
  301. function _tag_cdata( &$parser, $cdata ) {
  302. switch( $this->currentElement ) {
  303. // Table/field constraint
  304. case 'CONSTRAINT':
  305. if( isset( $this->current_field ) ) {
  306. $this->addFieldOpt( $this->current_field, $this->currentElement, $cdata );
  307. } else {
  308. $this->addTableOpt( $cdata );
  309. }
  310. break;
  311. // Table/field option
  312. case 'OPT':
  313. if( isset( $this->current_field ) ) {
  314. $this->addFieldOpt( $this->current_field, $cdata );
  315. } else {
  316. $this->addTableOpt( $cdata );
  317. }
  318. break;
  319. default:
  320. }
  321. }
  322. /**
  323. * XML Callback to process end elements
  324. *
  325. * @access private
  326. */
  327. function _tag_close( &$parser, $tag ) {
  328. $this->currentElement = '';
  329. switch( strtoupper( $tag ) ) {
  330. case 'TABLE':
  331. $this->parent->addSQL( $this->create( $this->parent ) );
  332. xml_set_object( $parser, $this->parent );
  333. $this->destroy();
  334. break;
  335. case 'FIELD':
  336. unset($this->current_field);
  337. break;
  338. case 'OPT':
  339. case 'CONSTRAINT':
  340. $this->currentPlatform = true;
  341. break;
  342. default:
  343. }
  344. }
  345. /**
  346. * Adds an index to a table object
  347. *
  348. * @param array $attributes Index attributes
  349. * @return object dbIndex object
  350. */
  351. function &addIndex( $attributes ) {
  352. $name = strtoupper( $attributes['NAME'] );
  353. $this->indexes[$name] = new dbIndex( $this, $attributes );
  354. return $this->indexes[$name];
  355. }
  356. /**
  357. * Adds data to a table object
  358. *
  359. * @param array $attributes Data attributes
  360. * @return object dbData object
  361. */
  362. function &addData( $attributes ) {
  363. if( !isset( $this->data ) ) {
  364. $this->data = new dbData( $this, $attributes );
  365. }
  366. return $this->data;
  367. }
  368. /**
  369. * Adds a field to a table object
  370. *
  371. * $name is the name of the table to which the field should be added.
  372. * $type is an ADODB datadict field type. The following field types
  373. * are supported as of ADODB 3.40:
  374. * - C: varchar
  375. * - X: CLOB (character large object) or largest varchar size
  376. * if CLOB is not supported
  377. * - C2: Multibyte varchar
  378. * - X2: Multibyte CLOB
  379. * - B: BLOB (binary large object)
  380. * - D: Date (some databases do not support this, and we return a datetime type)
  381. * - T: Datetime or Timestamp
  382. * - L: Integer field suitable for storing booleans (0 or 1)
  383. * - I: Integer (mapped to I4)
  384. * - I1: 1-byte integer
  385. * - I2: 2-byte integer
  386. * - I4: 4-byte integer
  387. * - I8: 8-byte integer
  388. * - F: Floating point number
  389. * - N: Numeric or decimal number
  390. *
  391. * @param string $name Name of the table to which the field will be added.
  392. * @param string $type ADODB datadict field type.
  393. * @param string $size Field size
  394. * @param array $opts Field options array
  395. * @return array Field specifier array
  396. */
  397. function addField( $name, $type, $size = NULL, $opts = NULL ) {
  398. $field_id = $this->FieldID( $name );
  399. // Set the field index so we know where we are
  400. $this->current_field = $field_id;
  401. // Set the field name (required)
  402. $this->fields[$field_id]['NAME'] = $name;
  403. // Set the field type (required)
  404. $this->fields[$field_id]['TYPE'] = $type;
  405. // Set the field size (optional)
  406. if( isset( $size ) ) {
  407. $this->fields[$field_id]['SIZE'] = $size;
  408. }
  409. // Set the field options
  410. if( isset( $opts ) ) {
  411. $this->fields[$field_id]['OPTS'] = array($opts);
  412. } else {
  413. $this->fields[$field_id]['OPTS'] = array();
  414. }
  415. }
  416. /**
  417. * Adds a field option to the current field specifier
  418. *
  419. * This method adds a field option allowed by the ADOdb datadict
  420. * and appends it to the given field.
  421. *
  422. * @param string $field Field name
  423. * @param string $opt ADOdb field option
  424. * @param mixed $value Field option value
  425. * @return array Field specifier array
  426. */
  427. function addFieldOpt( $field, $opt, $value = NULL ) {
  428. if( $this->currentPlatform ) {
  429. if( !isset( $value ) ) {
  430. $this->fields[$this->FieldID( $field )]['OPTS'][] = $opt;
  431. // Add the option and value
  432. } else {
  433. $this->fields[$this->FieldID( $field )]['OPTS'][] = array( $opt => $value );
  434. }
  435. }
  436. }
  437. /**
  438. * Adds an option to the table
  439. *
  440. * This method takes a comma-separated list of table-level options
  441. * and appends them to the table object.
  442. *
  443. * @param string $opt Table option
  444. * @return array Options
  445. */
  446. function addTableOpt( $opt ) {
  447. if( $this->currentPlatform ) {
  448. $this->opts[] = $opt;
  449. }
  450. return $this->opts;
  451. }
  452. /**
  453. * Generates the SQL that will create the table in the database
  454. *
  455. * @param object $xmls adoSchema object
  456. * @return array Array containing table creation SQL
  457. */
  458. function create( &$xmls ) {
  459. $sql = array();
  460. // drop any existing indexes
  461. if( is_array( $legacy_indexes = $xmls->dict->MetaIndexes( $this->name ) ) ) {
  462. foreach( $legacy_indexes as $index => $index_details ) {
  463. $sql[] = $xmls->dict->DropIndexSQL( $index, $this->name );
  464. }
  465. }
  466. // remove fields to be dropped from table object
  467. foreach( $this->drop_field as $field ) {
  468. unset( $this->fields[$field] );
  469. }
  470. // if table exists
  471. if( is_array( $legacy_fields = $xmls->dict->MetaColumns( $this->name ) ) ) {
  472. // drop table
  473. if( $this->drop_table ) {
  474. $sql[] = $xmls->dict->DropTableSQL( $this->name );
  475. return $sql;
  476. }
  477. // drop any existing fields not in schema
  478. foreach( $legacy_fields as $field_id => $field ) {
  479. if( !isset( $this->fields[$field_id] ) ) {
  480. $sql[] = $xmls->dict->DropColumnSQL( $this->name, $field->name );
  481. }
  482. }
  483. // if table doesn't exist
  484. } else {
  485. if( $this->drop_table ) {
  486. return $sql;
  487. }
  488. $legacy_fields = array();
  489. }
  490. // Loop through the field specifier array, building the associative array for the field options
  491. $fldarray = array();
  492. foreach( $this->fields as $field_id => $finfo ) {
  493. // Set an empty size if it isn't supplied
  494. if( !isset( $finfo['SIZE'] ) ) {
  495. $finfo['SIZE'] = '';
  496. }
  497. // Initialize the field array with the type and size
  498. $fldarray[$field_id] = array(
  499. 'NAME' => $finfo['NAME'],
  500. 'TYPE' => $finfo['TYPE'],
  501. 'SIZE' => $finfo['SIZE']
  502. );
  503. // Loop through the options array and add the field options.
  504. if( isset( $finfo['OPTS'] ) ) {
  505. foreach( $finfo['OPTS'] as $opt ) {
  506. // Option has an argument.
  507. if( is_array( $opt ) ) {
  508. $key = key( $opt );
  509. $value = $opt[key( $opt )];
  510. @$fldarray[$field_id][$key] .= $value;
  511. // Option doesn't have arguments
  512. } else {
  513. $fldarray[$field_id][$opt] = $opt;
  514. }
  515. }
  516. }
  517. }
  518. if( empty( $legacy_fields ) ) {
  519. // Create the new table
  520. $sql[] = $xmls->dict->CreateTableSQL( $this->name, $fldarray, $this->opts );
  521. logMsg( end( $sql ), 'Generated CreateTableSQL' );
  522. } else {
  523. // Upgrade an existing table
  524. logMsg( "Upgrading {$this->name} using '{$xmls->upgrade}'" );
  525. switch( $xmls->upgrade ) {
  526. // Use ChangeTableSQL
  527. case 'ALTER':
  528. logMsg( 'Generated ChangeTableSQL (ALTERing table)' );
  529. $sql[] = $xmls->dict->ChangeTableSQL( $this->name, $fldarray, $this->opts );
  530. break;
  531. case 'REPLACE':
  532. logMsg( 'Doing upgrade REPLACE (testing)' );
  533. $sql[] = $xmls->dict->DropTableSQL( $this->name );
  534. $sql[] = $xmls->dict->CreateTableSQL( $this->name, $fldarray, $this->opts );
  535. break;
  536. // ignore table
  537. default:
  538. return array();
  539. }
  540. }
  541. foreach( $this->indexes as $index ) {
  542. $sql[] = $index->create( $xmls );
  543. }
  544. if( isset( $this->data ) ) {
  545. $sql[] = $this->data->create( $xmls );
  546. }
  547. return $sql;
  548. }
  549. /**
  550. * Marks a field or table for destruction
  551. */
  552. function drop() {
  553. if( isset( $this->current_field ) ) {
  554. // Drop the current field
  555. logMsg( "Dropping field '{$this->current_field}' from table '{$this->name}'" );
  556. // $this->drop_field[$this->current_field] = $xmls->dict->DropColumnSQL( $this->name, $this->current_field );
  557. $this->drop_field[$this->current_field] = $this->current_field;
  558. } else {
  559. // Drop the current table
  560. logMsg( "Dropping table '{$this->name}'" );
  561. // $this->drop_table = $xmls->dict->DropTableSQL( $this->name );
  562. $this->drop_table = TRUE;
  563. }
  564. }
  565. }
  566. /**
  567. * Creates an index object in ADOdb's datadict format
  568. *
  569. * This class stores information about a database index. As charactaristics
  570. * of the index are loaded from the external source, methods and properties
  571. * of this class are used to build up the index description in ADOdb's
  572. * datadict format.
  573. *
  574. * @package axmls
  575. * @access private
  576. */
  577. class dbIndex extends dbObject {
  578. /**
  579. * @var string Index name
  580. */
  581. var $name;
  582. /**
  583. * @var array Index options: Index-level options
  584. */
  585. var $opts = array();
  586. /**
  587. * @var array Indexed fields: Table columns included in this index
  588. */
  589. var $columns = array();
  590. /**
  591. * @var boolean Mark index for destruction
  592. * @access private
  593. */
  594. var $drop = FALSE;
  595. /**
  596. * Initializes the new dbIndex object.
  597. *
  598. * @param object $parent Parent object
  599. * @param array $attributes Attributes
  600. *
  601. * @internal
  602. */
  603. function dbIndex( &$parent, $attributes = NULL ) {
  604. $this->parent = $parent;
  605. $this->name = $this->prefix ($attributes['NAME']);
  606. }
  607. /**
  608. * XML Callback to process start elements
  609. *
  610. * Processes XML opening tags.
  611. * Elements currently processed are: DROP, CLUSTERED, BITMAP, UNIQUE, FULLTEXT & HASH.
  612. *
  613. * @access private
  614. */
  615. function _tag_open( &$parser, $tag, $attributes ) {
  616. $this->currentElement = strtoupper( $tag );
  617. switch( $this->currentElement ) {
  618. case 'DROP':
  619. $this->drop();
  620. break;
  621. case 'CLUSTERED':
  622. case 'BITMAP':
  623. case 'UNIQUE':
  624. case 'FULLTEXT':
  625. case 'HASH':
  626. // Add index Option
  627. $this->addIndexOpt( $this->currentElement );
  628. break;
  629. default:
  630. // print_r( array( $tag, $attributes ) );
  631. }
  632. }
  633. /**
  634. * XML Callback to process CDATA elements
  635. *
  636. * Processes XML cdata.
  637. *
  638. * @access private
  639. */
  640. function _tag_cdata( &$parser, $cdata ) {
  641. switch( $this->currentElement ) {
  642. // Index field name
  643. case 'COL':
  644. $this->addField( $cdata );
  645. break;
  646. default:
  647. }
  648. }
  649. /**
  650. * XML Callback to process end elements
  651. *
  652. * @access private
  653. */
  654. function _tag_close( &$parser, $tag ) {
  655. $this->currentElement = '';
  656. switch( strtoupper( $tag ) ) {
  657. case 'INDEX':
  658. xml_set_object( $parser, $this->parent );
  659. break;
  660. }
  661. }
  662. /**
  663. * Adds a field to the index
  664. *
  665. * @param string $name Field name
  666. * @return string Field list
  667. */
  668. function addField( $name ) {
  669. $this->columns[$this->FieldID( $name )] = $name;
  670. // Return the field list
  671. return $this->columns;
  672. }
  673. /**
  674. * Adds options to the index
  675. *
  676. * @param string $opt Comma-separated list of index options.
  677. * @return string Option list
  678. */
  679. function addIndexOpt( $opt ) {
  680. $this->opts[] = $opt;
  681. // Return the options list
  682. return $this->opts;
  683. }
  684. /**
  685. * Generates the SQL that will create the index in the database
  686. *
  687. * @param object $xmls adoSchema object
  688. * @return array Array containing index creation SQL
  689. */
  690. function create( &$xmls ) {
  691. if( $this->drop ) {
  692. return NULL;
  693. }
  694. // eliminate any columns that aren't in the table
  695. foreach( $this->columns as $id => $col ) {
  696. if( !isset( $this->parent->fields[$id] ) ) {
  697. unset( $this->columns[$id] );
  698. }
  699. }
  700. return $xmls->dict->CreateIndexSQL( $this->name, $this->parent->name, $this->columns, $this->opts );
  701. }
  702. /**
  703. * Marks an index for destruction
  704. */
  705. function drop() {
  706. $this->drop = TRUE;
  707. }
  708. }
  709. /**
  710. * Creates a data object in ADOdb's datadict format
  711. *
  712. * This class stores information about table data, and is called
  713. * when we need to load field data into a table.
  714. *
  715. * @package axmls
  716. * @access private
  717. */
  718. class dbData extends dbObject {
  719. var $data = array();
  720. var $row;
  721. /**
  722. * Initializes the new dbData object.
  723. *
  724. * @param object $parent Parent object
  725. * @param array $attributes Attributes
  726. *
  727. * @internal
  728. */
  729. function dbData( &$parent, $attributes = NULL ) {
  730. $this->parent = $parent;
  731. }
  732. /**
  733. * XML Callback to process start elements
  734. *
  735. * Processes XML opening tags.
  736. * Elements currently processed are: ROW and F (field).
  737. *
  738. * @access private
  739. */
  740. function _tag_open( &$parser, $tag, $attributes ) {
  741. $this->currentElement = strtoupper( $tag );
  742. switch( $this->currentElement ) {
  743. case 'ROW':
  744. $this->row = count( $this->data );
  745. $this->data[$this->row] = array();
  746. break;
  747. case 'F':
  748. $this->addField($attributes);
  749. default:
  750. // print_r( array( $tag, $attributes ) );
  751. }
  752. }
  753. /**
  754. * XML Callback to process CDATA elements
  755. *
  756. * Processes XML cdata.
  757. *
  758. * @access private
  759. */
  760. function _tag_cdata( &$parser, $cdata ) {
  761. switch( $this->currentElement ) {
  762. // Index field name
  763. case 'F':
  764. $this->addData( $cdata );
  765. break;
  766. default:
  767. }
  768. }
  769. /**
  770. * XML Callback to process end elements
  771. *
  772. * @access private
  773. */
  774. function _tag_close( &$parser, $tag ) {
  775. $this->currentElement = '';
  776. switch( strtoupper( $tag ) ) {
  777. case 'DATA':
  778. xml_set_object( $parser, $this->parent );
  779. break;
  780. }
  781. }
  782. /**
  783. * Adds a field to the insert
  784. *
  785. * @param string $name Field name
  786. * @return string Field list
  787. */
  788. function addField( $attributes ) {
  789. // check we're in a valid row
  790. if( !isset( $this->row ) || !isset( $this->data[$this->row] ) ) {
  791. return;
  792. }
  793. // Set the field index so we know where we are
  794. if( isset( $attributes['NAME'] ) ) {
  795. $this->current_field = $this->FieldID( $attributes['NAME'] );
  796. } else {
  797. $this->current_field = count( $this->data[$this->row] );
  798. }
  799. // initialise data
  800. if( !isset( $this->data[$this->row][$this->current_field] ) ) {
  801. $this->data[$this->row][$this->current_field] = '';
  802. }
  803. }
  804. /**
  805. * Adds options to the index
  806. *
  807. * @param string $opt Comma-separated list of index options.
  808. * @return string Option list
  809. */
  810. function addData( $cdata ) {
  811. // check we're in a valid field
  812. if ( isset( $this->data[$this->row][$this->current_field] ) ) {
  813. // add data to field
  814. $this->data[$this->row][$this->current_field] .= $cdata;
  815. }
  816. }
  817. /**
  818. * Generates the SQL that will add/update the data in the database
  819. *
  820. * @param object $xmls adoSchema object
  821. * @return array Array containing index creation SQL
  822. */
  823. function create( &$xmls ) {
  824. $table = $xmls->dict->TableName($this->parent->name);
  825. $table_field_count = count($this->parent->fields);
  826. $tables = $xmls->db->MetaTables();
  827. $sql = array();
  828. $ukeys = $xmls->db->MetaPrimaryKeys( $table );
  829. if( !empty( $this->parent->indexes ) and !empty( $ukeys ) ) {
  830. foreach( $this->parent->indexes as $indexObj ) {
  831. if( !in_array( $indexObj->name, $ukeys ) ) $ukeys[] = $indexObj->name;
  832. }
  833. }
  834. // eliminate any columns that aren't in the table
  835. foreach( $this->data as $row ) {
  836. $table_fields = $this->parent->fields;
  837. $fields = array();
  838. $rawfields = array(); // Need to keep some of the unprocessed data on hand.
  839. foreach( $row as $field_id => $field_data ) {
  840. if( !array_key_exists( $field_id, $table_fields ) ) {
  841. if( is_numeric( $field_id ) ) {
  842. $field_id = reset( array_keys( $table_fields ) );
  843. } else {
  844. continue;
  845. }
  846. }
  847. $name = $table_fields[$field_id]['NAME'];
  848. switch( $table_fields[$field_id]['TYPE'] ) {
  849. case 'I':
  850. case 'I1':
  851. case 'I2':
  852. case 'I4':
  853. case 'I8':
  854. $fields[$name] = intval($field_data);
  855. break;
  856. case 'C':
  857. case 'C2':
  858. case 'X':
  859. case 'X2':
  860. default:
  861. $fields[$name] = $xmls->db->qstr( $field_data );
  862. $rawfields[$name] = $field_data;
  863. }
  864. unset($table_fields[$field_id]);
  865. }
  866. // check that at least 1 column is specified
  867. if( empty( $fields ) ) {
  868. continue;
  869. }
  870. // check that no required columns are missing
  871. if( count( $fields ) < $table_field_count ) {
  872. foreach( $table_fields as $field ) {
  873. if( isset( $field['OPTS'] ) and ( in_array( 'NOTNULL', $field['OPTS'] ) || in_array( 'KEY', $field['OPTS'] ) ) && !in_array( 'AUTOINCREMENT', $field['OPTS'] ) ) {
  874. continue(2);
  875. }
  876. }
  877. }
  878. // The rest of this method deals with updating existing data records.
  879. if( !in_array( $table, $tables ) or ( $mode = $xmls->existingData() ) == XMLS_MODE_INSERT ) {
  880. // Table doesn't yet exist, so it's safe to insert.
  881. logMsg( "$table doesn't exist, inserting or mode is INSERT" );
  882. $sql[] = 'INSERT INTO '. $table .' ('. implode( ',', array_keys( $fields ) ) .') VALUES ('. implode( ',', $fields ) .')';
  883. continue;
  884. }
  885. // Prepare to test for potential violations. Get primary keys and unique indexes
  886. $mfields = array_merge( $fields, $rawfields );
  887. $keyFields = array_intersect( $ukeys, array_keys( $mfields ) );
  888. if( empty( $ukeys ) or count( $keyFields ) == 0 ) {
  889. // No unique keys in schema, so safe to insert
  890. logMsg( "Either schema or data has no unique keys, so safe to insert" );
  891. $sql[] = 'INSERT INTO '. $table .' ('. implode( ',', array_keys( $fields ) ) .') VALUES ('. implode( ',', $fields ) .')';
  892. continue;
  893. }
  894. // Select record containing matching unique keys.
  895. $where = '';
  896. foreach( $ukeys as $key ) {
  897. if( isset( $mfields[$key] ) and $mfields[$key] ) {
  898. if( $where ) $where .= ' AND ';
  899. $where .= $key . ' = ' . $xmls->db->qstr( $mfields[$key] );
  900. }
  901. }
  902. $records = $xmls->db->Execute( 'SELECT * FROM ' . $table . ' WHERE ' . $where );
  903. switch( $records->RecordCount() ) {
  904. case 0:
  905. // No matching record, so safe to insert.
  906. logMsg( "No matching records. Inserting new row with unique data" );
  907. $sql[] = $xmls->db->GetInsertSQL( $records, $mfields );
  908. break;
  909. case 1:
  910. // Exactly one matching record, so we can update if the mode permits.
  911. logMsg( "One matching record..." );
  912. if( $mode == XMLS_MODE_UPDATE ) {
  913. logMsg( "...Updating existing row from unique data" );
  914. $sql[] = $xmls->db->GetUpdateSQL( $records, $mfields );
  915. }
  916. break;
  917. default:
  918. // More than one matching record; the result is ambiguous, so we must ignore the row.
  919. logMsg( "More than one matching record. Ignoring row." );
  920. }
  921. }
  922. return $sql;
  923. }
  924. }
  925. /**
  926. * Creates the SQL to execute a list of provided SQL queries
  927. *
  928. * @package axmls
  929. * @access private
  930. */
  931. class dbQuerySet extends dbObject {
  932. /**
  933. * @var array List of SQL queries
  934. */
  935. var $queries = array();
  936. /**
  937. * @var string String used to build of a query line by line
  938. */
  939. var $query;
  940. /**
  941. * @var string Query prefix key
  942. */
  943. var $prefixKey = '';
  944. /**
  945. * @var boolean Auto prefix enable (TRUE)
  946. */
  947. var $prefixMethod = 'AUTO';
  948. /**
  949. * Initializes the query set.
  950. *
  951. * @param object $parent Parent object
  952. * @param array $attributes Attributes
  953. */
  954. function dbQuerySet( &$parent, $attributes = NULL ) {
  955. $this->parent = $parent;
  956. // Overrides the manual prefix key
  957. if( isset( $attributes['KEY'] ) ) {
  958. $this->prefixKey = $attributes['KEY'];
  959. }
  960. $prefixMethod = isset( $attributes['PREFIXMETHOD'] ) ? strtoupper( trim( $attributes['PREFIXMETHOD'] ) ) : '';
  961. // Enables or disables automatic prefix prepending
  962. switch( $prefixMethod ) {
  963. case 'AUTO':
  964. $this->prefixMethod = 'AUTO';
  965. break;
  966. case 'MANUAL':
  967. $this->prefixMethod = 'MANUAL';
  968. break;
  969. case 'NONE':
  970. $this->prefixMethod = 'NONE';
  971. break;
  972. }
  973. }
  974. /**
  975. * XML Callback to process start elements. Elements currently
  976. * processed are: QUERY.
  977. *
  978. * @access private
  979. */
  980. function _tag_open( &$parser, $tag, $attributes ) {
  981. $this->currentElement = strtoupper( $tag );
  982. switch( $this->currentElement ) {
  983. case 'QUERY':
  984. // Create a new query in a SQL queryset.
  985. // Ignore this query set if a platform is specified and it's different than the
  986. // current connection platform.
  987. if( !isset( $attributes['PLATFORM'] ) OR $this->supportedPlatform( $attributes['PLATFORM'] ) ) {
  988. $this->newQuery();
  989. } else {
  990. $this->discardQuery();
  991. }
  992. break;
  993. default:
  994. // print_r( array( $tag, $attributes ) );
  995. }
  996. }
  997. /**
  998. * XML Callback to process CDATA elements
  999. */
  1000. function _tag_cdata( &$parser, $cdata ) {
  1001. switch( $this->currentElement ) {
  1002. // Line of queryset SQL data
  1003. case 'QUERY':
  1004. $this->buildQuery( $cdata );
  1005. break;
  1006. default:
  1007. }
  1008. }
  1009. /**
  1010. * XML Callback to process end elements
  1011. *
  1012. * @access private
  1013. */
  1014. function _tag_close( &$parser, $tag ) {
  1015. $this->currentElement = '';
  1016. switch( strtoupper( $tag ) ) {
  1017. case 'QUERY':
  1018. // Add the finished query to the open query set.
  1019. $this->addQuery();
  1020. break;
  1021. case 'SQL':
  1022. $this->parent->addSQL( $this->create( $this->parent ) );
  1023. xml_set_object( $parser, $this->parent );
  1024. $this->destroy();
  1025. break;
  1026. default:
  1027. }
  1028. }
  1029. /**
  1030. * Re-initializes the query.
  1031. *
  1032. * @return boolean TRUE
  1033. */
  1034. function newQuery() {
  1035. $this->query = '';
  1036. return TRUE;
  1037. }
  1038. /**
  1039. * Discards the existing query.
  1040. *
  1041. * @return boolean TRUE
  1042. */
  1043. function discardQuery() {
  1044. unset( $this->query );
  1045. return TRUE;
  1046. }
  1047. /**
  1048. * Appends a line to a query that is being built line by line
  1049. *
  1050. * @param string $data Line of SQL data or NULL to initialize a new query
  1051. * @return string SQL query string.
  1052. */
  1053. function buildQuery( $sql = NULL ) {
  1054. if( !isset( $this->query ) OR empty( $sql ) ) {
  1055. return FALSE;
  1056. }
  1057. $this->query .= $sql;
  1058. return $this->query;
  1059. }
  1060. /**
  1061. * Adds a completed query to the query list
  1062. *
  1063. * @return string SQL of added query
  1064. */
  1065. function addQuery() {
  1066. if( !isset( $this->query ) ) {
  1067. return FALSE;
  1068. }
  1069. $this->queries[] = $return = trim($this->query);
  1070. unset( $this->query );
  1071. return $return;
  1072. }
  1073. /**
  1074. * Creates and returns the current query set
  1075. *
  1076. * @param object $xmls adoSchema object
  1077. * @return array Query set
  1078. */
  1079. function create( &$xmls ) {
  1080. foreach( $this->queries as $id => $query ) {
  1081. switch( $this->prefixMethod ) {
  1082. case 'AUTO':
  1083. // Enable auto prefix replacement
  1084. // Process object prefix.
  1085. // Evaluate SQL statements to prepend prefix to objects
  1086. $query = $this->prefixQuery( '/^\s*((?is)INSERT\s+(INTO\s+)?)((\w+\s*,?\s*)+)(\s.*$)/', $query, $xmls->objectPrefix );
  1087. $query = $this->prefixQuery( '/^\s*((?is)UPDATE\s+(FROM\s+)?)((\w+\s*,?\s*)+)(\s.*$)/', $query, $xmls->objectPrefix );
  1088. $query = $this->prefixQuery( '/^\s*((?is)DELETE\s+(FROM\s+)?)((\w+\s*,?\s*)+)(\s.*$)/', $query, $xmls->objectPrefix );
  1089. // SELECT statements aren't working yet
  1090. #$data = preg_replace( '/(?ias)(^\s*SELECT\s+.*\s+FROM)\s+(\W\s*,?\s*)+((?i)\s+WHERE.*$)/', "\1 $prefix\2 \3", $data );
  1091. case 'MANUAL':
  1092. // If prefixKey is set and has a value then we use it to override the default constant XMLS_PREFIX.
  1093. // If prefixKey is not set, we use the default constant XMLS_PREFIX
  1094. if( isset( $this->prefixKey ) AND( $this->prefixKey !== '' ) ) {
  1095. // Enable prefix override
  1096. $query = str_replace( $this->prefixKey, $xmls->objectPrefix, $query );
  1097. } else {
  1098. // Use default replacement
  1099. $query = str_replace( XMLS_PREFIX , $xmls->objectPrefix, $query );
  1100. }
  1101. }
  1102. $this->queries[$id] = trim( $query );
  1103. }
  1104. // Return the query set array
  1105. return $this->queries;
  1106. }
  1107. /**
  1108. * Rebuilds the query with the prefix attached to any objects
  1109. *
  1110. * @param string $regex Regex used to add prefix
  1111. * @param string $query SQL query string
  1112. * @param string $prefix Prefix to be appended to tables, indices, etc.
  1113. * @return string Prefixed SQL query string.
  1114. */
  1115. function prefixQuery( $regex, $query, $prefix = NULL ) {
  1116. if( !isset( $prefix ) ) {
  1117. return $query;
  1118. }
  1119. if( preg_match( $regex, $query, $match ) ) {
  1120. $preamble = $match[1];
  1121. $postamble = $match[5];
  1122. $objectList = explode( ',', $match[3] );
  1123. // $prefix = $prefix . '_';
  1124. $prefixedList = '';
  1125. foreach( $objectList as $object ) {
  1126. if( $prefixedList !== '' ) {
  1127. $prefixedList .= ', ';
  1128. }
  1129. $prefixedList .= $prefix . trim( $object );
  1130. }
  1131. $query = $preamble . ' ' . $prefixedList . ' ' . $postamble;
  1132. }
  1133. return $query;
  1134. }
  1135. }
  1136. /**
  1137. * Loads and parses an XML file, creating an array of "ready-to-run" SQL statements
  1138. *
  1139. * This class is used to load and parse the XML file, to create an array of SQL statements
  1140. * that can be used to build a database, and to build the database using the SQL array.
  1141. *
  1142. * @tutorial getting_started.pkg
  1143. *
  1144. * @author Richard Tango-Lowy & Dan Cech
  1145. * @version $Revision: 1.62 $
  1146. *
  1147. * @package axmls
  1148. */
  1149. class adoSchema {
  1150. /**
  1151. * @var array Array containing SQL queries to generate all objects
  1152. * @access private
  1153. */
  1154. var $sqlArray;
  1155. /**
  1156. * @var object ADOdb connection object
  1157. * @access private
  1158. */
  1159. var $db;
  1160. /**
  1161. * @var object ADOdb Data Dictionary
  1162. * @access private
  1163. */
  1164. var $dict;
  1165. /**
  1166. * @var string Current XML element
  1167. * @access private
  1168. */
  1169. var $currentElement = '';
  1170. /**
  1171. * @var string If set (to 'ALTER' or 'REPLACE'), upgrade an existing database
  1172. * @access private
  1173. */
  1174. var $upgrade = '';
  1175. /**
  1176. * @var string Optional object prefix
  1177. * @access private
  1178. */
  1179. var $objectPrefix = '';
  1180. /**
  1181. * @var long Original Magic Quotes Runtime value
  1182. * @access private
  1183. */
  1184. var $mgq;
  1185. /**
  1186. * @var long System debug
  1187. * @access private
  1188. */
  1189. var $debug;
  1190. /**
  1191. * @var string Regular expression to find schema version
  1192. * @access private
  1193. */
  1194. var $versionRegex = '/<schema.*?( version="([^"]*)")?.*?>/';
  1195. /**
  1196. * @var string Current schema version
  1197. * @access private
  1198. */
  1199. var $schemaVersion;
  1200. /**
  1201. * @var int Success of last Schema execution
  1202. */
  1203. var $success;
  1204. /**
  1205. * @var bool Execute SQL inline as it is generated
  1206. */
  1207. var $executeInline;
  1208. /**
  1209. * @var bool Continue SQL execution if errors occur
  1210. */
  1211. var $continueOnError;
  1212. /**
  1213. * @var int How to handle existing data rows (insert, update, or ignore)
  1214. */
  1215. var $existingData;
  1216. /**
  1217. * Creates an adoSchema object
  1218. *
  1219. * Creating an adoSchema object is the first step in processing an XML schema.
  1220. * The only parameter is an ADOdb database connection object, which must already
  1221. * have been created.
  1222. *
  1223. * @param object $db ADOdb database connection object.
  1224. */
  1225. function adoSchema( &$db ) {
  1226. // Initialize the environment
  1227. $this->mgq = get_magic_quotes_runtime();
  1228. set_magic_quotes_runtime(0);
  1229. $this->db = $db;
  1230. $this->debug = $this->db->debug;
  1231. $this->dict = NewDataDictionary( $this->db );
  1232. $this->sqlArray = array();
  1233. $this->schemaVersion = XMLS_SCHEMA_VERSION;
  1234. $this->executeInline( XMLS_EXECUTE_INLINE );
  1235. $this->continueOnError( XMLS_CONTINUE_ON_ERROR );
  1236. $this->existingData( XMLS_EXISTING_DATA );
  1237. $this->setUpgradeMethod();
  1238. }
  1239. /**
  1240. * Sets the method to be used for upgrading an existing database
  1241. *
  1242. * Use this method to specify how existing database objects should be upgraded.
  1243. * The method option can be set to ALTER, REPLACE, BEST, or NONE. ALTER attempts to
  1244. * alter each database object directly, REPLACE attempts to rebuild each object
  1245. * from scratch, BEST attempts to determine the best upgrade method for each
  1246. * object, and NONE disables upgrading.
  1247. *
  1248. * This method is not yet used by AXMLS, but exists for backward compatibility.
  1249. * The ALTER method is automatically assumed when the adoSchema object is
  1250. * instantiated; other upgrade methods are not currently supported.
  1251. *
  1252. * @param string $method Upgrade method (ALTER|REPLACE|BEST|NONE)
  1253. * @returns string Upgrade method used
  1254. */
  1255. function SetUpgradeMethod( $method = '' ) {
  1256. if( !is_string( $method ) ) {
  1257. return FALSE;
  1258. }
  1259. $method = strtoupper( $method );
  1260. // Handle the upgrade methods
  1261. switch( $method ) {
  1262. case 'ALTER':
  1263. $this->upgrade = $method;
  1264. break;
  1265. case 'REPLACE':
  1266. $this->upgrade = $method;
  1267. break;
  1268. case 'BEST':
  1269. $this->upgrade = 'ALTER';
  1270. break;
  1271. case 'NONE':
  1272. $this->upgrade = 'NONE';
  1273. break;
  1274. default:
  1275. // Use default if no legitimate method is passed.
  1276. $this->upgrade = XMLS_DEFAULT_UPGRADE_METHOD;
  1277. }
  1278. return $this->upgrade;
  1279. }
  1280. /**
  1281. * Specifies how to handle existing data row when there is a unique key conflict.
  1282. *
  1283. * The existingData setting specifies how the parser should handle existing rows
  1284. * when a unique key violation occurs during the insert. This can happen when inserting
  1285. * data into an existing table with one or more primary keys or unique indexes.
  1286. * The existingData method takes one of three options: XMLS_MODE_INSERT attempts
  1287. * to always insert the data as a new row. In the event of a unique key violation,
  1288. * the database will generate an error. XMLS_MODE_UPDATE attempts to update the
  1289. * any existing rows with the new data based upon primary or unique key fields in
  1290. * the schema. If the data row in the schema specifies no unique fields, the row
  1291. * data will be inserted as a new row. XMLS_MODE_IGNORE specifies that any data rows
  1292. * that would result in a unique key violation be ignored; no inserts or updates will
  1293. * take place. For backward compatibility, the default setting is XMLS_MODE_INSERT,
  1294. * but XMLS_MODE_UPDATE will generally be the most appropriate setting.
  1295. *
  1296. * @param int $mode XMLS_MODE_INSERT, XMLS_MODE_UPDATE, or XMLS_MODE_IGNORE
  1297. * @return int current mode
  1298. */
  1299. function ExistingData( $mode = NULL ) {
  1300. if( is_int( $mode ) ) {
  1301. switch( $mode ) {
  1302. case XMLS_MODE_UPDATE:
  1303. $mode = XMLS_MODE_UPDATE;
  1304. break;
  1305. case XMLS_MODE_IGNORE:
  1306. $mode = XMLS_MODE_IGNORE;
  1307. break;
  1308. case XMLS_MODE_INSERT:
  1309. $mode = XMLS_MODE_INSERT;
  1310. break;
  1311. default:
  1312. $mode = XMLS_EXISITNG_DATA;
  1313. break;
  1314. }
  1315. $this->existingData = $mode;
  1316. }
  1317. return $this->existingData;
  1318. }
  1319. /**
  1320. * Enables/disables inline SQL execution.
  1321. *
  1322. * Call this method to enable or disable inline execution of the schema. If the mode is set to TRUE (inline execution),
  1323. * AXMLS applies the SQL to the database immediately as each schema entity is parsed. If the mode
  1324. * is set to FALSE (post execution), AXMLS parses the entire schema and you will need to call adoSchema::ExecuteSchema()
  1325. * to apply the schema to the database.
  1326. *
  1327. * @param bool $mode execute
  1328. * @return bool current execution mode
  1329. *
  1330. * @see ParseSchema(), ExecuteSchema()
  1331. */
  1332. function ExecuteInline( $mode = NULL ) {
  1333. if( is_bool( $mode ) ) {
  1334. $this->executeInline = $mode;
  1335. }
  1336. return $this->executeInline;
  1337. }
  1338. /**
  1339. * Enables/disables SQL continue on error.
  1340. *
  1341. * Call this method to enable or disable continuation of SQL execution if an error occurs.
  1342. * If the mode is set to TRUE (continue), AXMLS will continue to apply SQL to the database, even if an error occurs.
  1343. * If the mode is set to FALSE (halt), AXMLS will halt execution of generated sql if an error occurs, though parsing
  1344. * of the schema will continue.
  1345. *
  1346. * @param bool $mode execute
  1347. * @return bool current continueOnError mode
  1348. *
  1349. * @see addSQL(), ExecuteSchema()
  1350. */
  1351. function ContinueOnError( $mode = NULL ) {
  1352. if( is_bool( $mode ) ) {
  1353. $this->continueOnError = $mode;
  1354. }
  1355. return $this->continueOnError;
  1356. }
  1357. /**
  1358. * Loads an XML schema from a file and converts it to SQL.
  1359. *
  1360. * Call this method to load the specified schema (see the DTD for the proper format) from
  1361. * the filesystem and generate the SQL necessary to create the database
  1362. * described. This method automatically converts the schema to the latest
  1363. * axmls schema version.
  1364. * @see ParseSchemaString()
  1365. *
  1366. * @param string $file Name of XML schema file.
  1367. * @param bool $returnSchema Return schema rather than parsing.
  1368. * @return array Array of SQL queries, ready to execute
  1369. */
  1370. function ParseSchema( $filename, $returnSchema = FALSE ) {
  1371. return $this->ParseSchemaString( $this->ConvertSchemaFile( $filename ), $returnSchema );
  1372. }
  1373. /**
  1374. * Loads an XML schema from a file and converts it to SQL.
  1375. *
  1376. * Call this method to load the specified schema directly from a file (see
  1377. * the DTD for the proper format) and generate the SQL necessary to create
  1378. * the database described by the schema. Use this method when you are dealing
  1379. * with large schema files. Otherwise, ParseSchema() is faster.
  1380. * This method does not automatically convert the schema to the latest axmls
  1381. * schema version. You must convert the schema manually using either the
  1382. * ConvertSchemaFile() or ConvertSchemaString() method.
  1383. * @see ParseSchema()
  1384. * @see ConvertSchemaFile()
  1385. * @see ConvertSchemaString()
  1386. *
  1387. * @param string $file Name of XML schema file.
  1388. * @param bool $returnSchema Return schema rather than parsing.
  1389. * @return array Array of SQL queries, ready to execute.
  1390. *
  1391. * @deprecated Replaced by adoSchema::ParseSchema() and adoSchema::ParseSchemaString()
  1392. * @see ParseSchema(), ParseSchemaString()
  1393. */
  1394. function ParseSchemaFile( $filename, $returnSchema = FALSE ) {
  1395. // Open the file
  1396. if( !($fp = fopen( $filename, 'r' )) ) {
  1397. logMsg( 'Unable to open file' );
  1398. return FALSE;
  1399. }
  1400. // do version detection here
  1401. if( $this->SchemaFileVersion( $filename ) != $this->schemaVersion ) {
  1402. logMsg( 'Invalid Schema Version' );
  1403. return FALSE;
  1404. }
  1405. if( $returnSchema ) {
  1406. $xmlstring = '';
  1407. while( $data = fread( $fp, 4096 ) ) {
  1408. $xmlstring .= $data . "\n";
  1409. }
  1410. return $xmlstring;
  1411. }
  1412. $this->success = 2;
  1413. $xmlParser = $this->create_parser();
  1414. // Process the file
  1415. while( $data = fread( $fp, 4096 ) ) {
  1416. if( !xml_parse( $xmlParser, $data, feof( $fp ) ) ) {
  1417. die( sprintf(
  1418. "XML error: %s at line %d",
  1419. xml_error_string( xml_get_error_code( $xmlParser) ),
  1420. xml_get_current_line_number( $xmlParser)
  1421. ) );
  1422. }
  1423. }
  1424. xml_parser_free( $xmlParser );
  1425. return $this->sqlArray;
  1426. }
  1427. /**
  1428. * Converts an XML schema string to SQL.
  1429. *
  1430. * Call this method to parse a string containing an XML schema (see the DTD for the proper format)
  1431. * and generate the SQL necessary to create the database described by the schema.
  1432. * @see ParseSchema()
  1433. *
  1434. * @param string $xmlstring XML schema string.
  1435. * @param bool $returnSchema Return schema rather than parsing.
  1436. * @return array Array of SQL queries, ready to execute.
  1437. */
  1438. function ParseSchemaString( $xmlstring, $returnSchema = FALSE ) {
  1439. if( !is_string( $xmlstring ) OR empty( $xmlstring ) ) {
  1440. logMsg( 'Empty or Invalid Schema' );
  1441. return FALSE;
  1442. }
  1443. // do version detection here
  1444. if( $this->SchemaStringVersion( $xmlstring ) != $this->schemaVersion ) {
  1445. logMsg( 'Invalid Schema Version' );
  1446. return FALSE;
  1447. }
  1448. if( $returnSchema ) {
  1449. return $xmlstring;
  1450. }
  1451. $this->success = 2;
  1452. $xmlParser = $this->create_parser();
  1453. if( !xml_parse( $xmlParser, $xmlstring, TRUE ) ) {
  1454. die( sprintf(
  1455. "XML error: %s at line %d",
  1456. xml_error_string( xml_get_error_code( $xmlParser) ),
  1457. xml_get_current_line_number( $xmlParser)
  1458. ) );
  1459. }
  1460. xml_parser_free( $xmlParser );
  1461. return $this->sqlArray;
  1462. }
  1463. /**
  1464. * Loads an XML schema from a file and converts it to uninstallation SQL.
  1465. *
  1466. * Call this method to load the specified schema (see the DTD for the proper format) from
  1467. * the filesystem and generate the SQL necessary to remove the database described.
  1468. * @see RemoveSchemaString()
  1469. *
  1470. * @param string $file Name of XML schema file.
  1471. * @param bool $returnSchema Return schema rather than parsing.
  1472. * @return array Array of SQL queries, ready to execute
  1473. */
  1474. function RemoveSchema( $filename, $returnSchema = FALSE ) {
  1475. return $this->RemoveSchemaString( $this->ConvertSchemaFile( $filename ), $returnSchema );
  1476. }
  1477. /**
  1478. * Converts an XML schema string to uninstallation SQL.
  1479. *
  1480. * Call this method to parse a string containing an XML schema (see the DTD for the proper format)
  1481. * and generate the SQL necessary to uninstall the database described by the schema.
  1482. * @see RemoveSchema()
  1483. *
  1484. * @param string $schema XML schema string.
  1485. * @param bool $returnSchema Return schema rather than parsing.
  1486. * @return array Array of SQL queries, ready to execute.
  1487. */
  1488. function RemoveSchemaString( $schema, $returnSchema = FALSE ) {
  1489. // grab current version
  1490. if( !( $version = $this->SchemaStringVersion( $schema ) ) ) {
  1491. return FALSE;
  1492. }
  1493. return $this->ParseSchemaString( $this->TransformSchema( $schema, 'remove-' . $version), $returnSchema );
  1494. }
  1495. /**
  1496. * Applies the current XML schema to the database (post execution).
  1497. *
  1498. * Call this method to apply the current schema (generally created by calling
  1499. * ParseSchema() or ParseSchemaString() ) to the database (creating the tables, indexes,
  1500. * and executing other SQL specified in the schema) after parsing.
  1501. * @see ParseSchema(), ParseSchemaString(), ExecuteInline()
  1502. *
  1503. * @param array $sqlArray Array of SQL statements that will be applied rather than
  1504. * the current schema.
  1505. * @param boolean $continueOnErr Continue to apply the schema even if an error occurs.
  1506. * @returns integer 0 if failure, 1 if errors, 2 if successful.
  1507. */
  1508. function ExecuteSchema( $sqlArray = NULL, $continueOnErr = NULL ) {
  1509. if( !is_bool( $continueOnErr ) ) {
  1510. $continueOnErr = $this->ContinueOnError();
  1511. }
  1512. if( !isset( $sqlArray ) ) {
  1513. $sqlArray = $this->sqlArray;
  1514. }
  1515. if( !is_array( $sqlArray ) ) {
  1516. $this->success = 0;
  1517. } else {
  1518. $this->success = $this->dict->ExecuteSQLArray( $sqlArray, $continueOnErr );
  1519. }
  1520. return $this->success;
  1521. }
  1522. /**
  1523. * Returns the current SQL array.
  1524. *
  1525. * Call this method to fetch the array of SQL queries resulting from
  1526. * ParseSchema() or ParseSchemaString().
  1527. *
  1528. * @param string $format Format: HTML, TEXT, or NONE (PHP array)
  1529. * @return array Array of SQL statements or FALSE if an error occurs
  1530. */
  1531. function PrintSQL( $format = 'NONE' ) {
  1532. $sqlArray = null;
  1533. return $this->getSQL( $format, $sqlArray );
  1534. }
  1535. /**
  1536. * Saves the current SQL array to the local filesystem as a list of SQL queries.
  1537. *
  1538. * Call this method to save the array of SQL queries (generally resulting from a
  1539. * parsed XML schema) to the filesystem.
  1540. *
  1541. * @param string $filename Path and name where the file should be saved.
  1542. * @return boolean TRUE if save is successful, else FALSE.
  1543. */
  1544. function SaveSQL( $filename = './schema.sql' ) {
  1545. if( !isset( $sqlArray ) ) {
  1546. $sqlArray = $this->sqlArray;
  1547. }
  1548. if( !isset( $sqlArray ) ) {
  1549. return FALSE;
  1550. }
  1551. $fp = fopen( $filename, "w" );
  1552. foreach( $sqlArray as $key => $query ) {
  1553. fwrite( $fp, $query . ";\n" );
  1554. }
  1555. fclose( $fp );
  1556. }
  1557. /**
  1558. * Create an xml parser
  1559. *
  1560. * @return object PHP XML parser object
  1561. *
  1562. * @access private
  1563. */
  1564. function &create_parser() {
  1565. // Create the parser
  1566. $xmlParser = xml_parser_create();
  1567. xml_set_object( $xmlParser, $this );
  1568. // Initialize the XML callback functions
  1569. xml_set_element_handler( $xmlParser, '_tag_open', '_tag_close' );
  1570. xml_set_character_data_handler( $xmlParser, '_tag_cdata' );
  1571. return $xmlParser;
  1572. }
  1573. /**
  1574. * XML Callback to process start elements
  1575. *
  1576. * @access private
  1577. */
  1578. function _tag_open( &$parser, $tag, $attributes ) {
  1579. switch( strtoupper( $tag ) ) {
  1580. case 'TABLE':
  1581. if( !isset( $attributes['PLATFORM'] ) OR $this->supportedPlatform( $attributes['PLATFORM'] ) ) {
  1582. $this->obj = new dbTable( $this, $attributes );
  1583. xml_set_object( $parser, $this->obj );
  1584. }
  1585. break;
  1586. case 'SQL':
  1587. if( !isset( $attributes['PLATFORM'] ) OR $this->supportedPlatform( $attributes['PLATFORM'] ) ) {
  1588. $this->obj = new dbQuerySet( $this, $attributes );
  1589. xml_set_object( $parser, $this->obj );
  1590. }
  1591. break;
  1592. default:
  1593. // print_r( array( $tag, $attributes ) );
  1594. }
  1595. }
  1596. /**
  1597. * XML Callback to process CDATA elements
  1598. *
  1599. * @access private
  1600. */
  1601. function _tag_cdata( &$parser, $cdata ) {
  1602. }
  1603. /**
  1604. * XML Callback to process end elements
  1605. *
  1606. * @access private
  1607. * @internal
  1608. */
  1609. function _tag_close( &$parser, $tag ) {
  1610. }
  1611. /**
  1612. * Converts an XML schema string to the specified DTD version.
  1613. *
  1614. * Call this method to convert a string containing an XML schema to a different AXMLS
  1615. * DTD version. For instance, to convert a schema created for an pre-1.0 version for
  1616. * AXMLS (DTD version 0.1) to a newer version of the DTD (e.g. 0.2). If no DTD version
  1617. * parameter is specified, the schema will be converted to the current DTD version.
  1618. * If the newFile parameter is provided, the converted schema will be written to the specified
  1619. * file.
  1620. * @see ConvertSchemaFile()
  1621. *
  1622. * @param string $schema String containing XML schema that will be converted.
  1623. * @param string $newVersion DTD version to convert to.
  1624. * @param string $newFile File name of (converted) output file.
  1625. * @return string Converted XML schema or FALSE if an error occurs.
  1626. */
  1627. function ConvertSchemaString( $schema, $newVersion = NULL, $newFile = NULL ) {
  1628. // grab current version
  1629. if( !( $version = $this->SchemaStringVersion( $schema ) ) ) {
  1630. return FALSE;
  1631. }
  1632. if( !isset ($newVersion) ) {
  1633. $newVersion = $this->schemaVersion;
  1634. }
  1635. if( $version == $newVersion ) {
  1636. $result = $schema;
  1637. } else {
  1638. $result = $this->TransformSchema( $schema, 'convert-' . $version . '-' . $newVersion);
  1639. }
  1640. if( is_string( $result ) AND is_string( $newFile ) AND ( $fp = fopen( $newFile, 'w' ) ) ) {
  1641. fwrite( $fp, $result );
  1642. fclose( $fp );
  1643. }
  1644. return $result;
  1645. }
  1646. /*
  1647. // compat for pre-4.3 - jlim
  1648. function _file_get_contents($path)
  1649. {
  1650. if (function_exists('file_get_contents')) return file_get_contents($path);
  1651. return join('',file($path));
  1652. }*/
  1653. /**
  1654. * Converts an XML schema file to the specified DTD version.
  1655. *
  1656. * Call this method to convert the specified XML schema file to a different AXMLS
  1657. * DTD version. For instance, to convert a schema created for an pre-1.0 version for
  1658. * AXMLS (DTD version 0.1) to a newer version of the DTD (e.g. 0.2). If no DTD version
  1659. * parameter is specified, the schema will be converted to the current DTD version.
  1660. * If the newFile parameter is provided, the converted schema will be written to the specified
  1661. * file.
  1662. * @see ConvertSchemaString()
  1663. *
  1664. * @param string $filename Name of XML schema file that will be converted.
  1665. * @param string $newVersion DTD version to convert to.
  1666. * @param string $newFile File name of (converted) output file.
  1667. * @return string Converted XML schema or FALSE if an error occurs.
  1668. */
  1669. function ConvertSchemaFile( $filename, $newVersion = NULL, $newFile = NULL ) {
  1670. // grab current version
  1671. if( !( $version = $this->SchemaFileVersion( $filename ) ) ) {
  1672. return FALSE;
  1673. }
  1674. if( !isset ($newVersion) ) {
  1675. $newVersion = $this->schemaVersion;
  1676. }
  1677. if( $version == $newVersion ) {
  1678. $result = _file_get_contents( $filename );
  1679. // re…

Large files files are truncated, but you can click here to view the full file