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 *******************************************************************************/
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
13 * Last Editor: $Author$
14 * @author Richard Tango-Lowy & Dan Cech
18 * @tutorial getting_started.pkg
21 function _file_get_contents($file)
23 if (function_exists('file_get_contents')) return file_get_contents($file);
25 $f = fopen($file,'r');
29 while ($s = fread($f,100000)) $t .= $s;
38 if( !defined( 'XMLS_DEBUG' ) ) {
39 define( 'XMLS_DEBUG', FALSE );
45 if( !defined( 'XMLS_PREFIX' ) ) {
46 define( 'XMLS_PREFIX', '%%P' );
50 * Maximum length allowed for object prefix
52 if( !defined( 'XMLS_PREFIX_MAXLEN' ) ) {
53 define( 'XMLS_PREFIX_MAXLEN', 10 );
57 * Execute SQL inline as it is generated
59 if( !defined( 'XMLS_EXECUTE_INLINE' ) ) {
60 define( 'XMLS_EXECUTE_INLINE', FALSE );
64 * Continue SQL Execution if an error occurs?
66 if( !defined( 'XMLS_CONTINUE_ON_ERROR' ) ) {
67 define( 'XMLS_CONTINUE_ON_ERROR', FALSE );
71 * Current Schema Version
73 if( !defined( 'XMLS_SCHEMA_VERSION' ) ) {
74 define( 'XMLS_SCHEMA_VERSION', '0.3' );
78 * Default Schema Version. Used for Schemas without an explicit version set.
80 if( !defined( 'XMLS_DEFAULT_SCHEMA_VERSION' ) ) {
81 define( 'XMLS_DEFAULT_SCHEMA_VERSION', '0.1' );
85 * How to handle data rows that already exist in a database during and upgrade.
86 * Options are INSERT (attempts to insert duplicate rows), UPDATE (updates existing
87 * rows) and IGNORE (ignores existing rows).
89 if( !defined( 'XMLS_MODE_INSERT' ) ) {
90 define( 'XMLS_MODE_INSERT', 0 );
92 if( !defined( 'XMLS_MODE_UPDATE' ) ) {
93 define( 'XMLS_MODE_UPDATE', 1 );
95 if( !defined( 'XMLS_MODE_IGNORE' ) ) {
96 define( 'XMLS_MODE_IGNORE', 2 );
98 if( !defined( 'XMLS_EXISTING_DATA' ) ) {
99 define( 'XMLS_EXISTING_DATA', XMLS_MODE_INSERT
);
103 * Default Schema Version. Used for Schemas without an explicit version set.
105 if( !defined( 'XMLS_DEFAULT_UPGRADE_METHOD' ) ) {
106 define( 'XMLS_DEFAULT_UPGRADE_METHOD', 'ALTER' );
110 * Include the main ADODB library
112 if( !defined( '_ADODB_LAYER' ) ) {
113 require( 'adodb.inc.php' );
114 require( 'adodb-datadict.inc.php' );
118 * Abstract DB Object. This class provides basic methods for database objects, such
119 * as tables and indexes.
132 * var string current element
139 function dbObject( &$parent, $attributes = NULL ) {
140 $this->parent
=& $parent;
144 * XML Callback to process start elements
148 function _tag_open( &$parser, $tag, $attributes ) {
153 * XML Callback to process CDATA elements
157 function _tag_cdata( &$parser, $cdata ) {
162 * XML Callback to process end elements
166 function _tag_close( &$parser, $tag ) {
175 * Destroys the object
182 * Checks whether the specified RDBMS is supported by the current
183 * database object or its ranking ancestor.
185 * @param string $platform RDBMS platform name (from ADODB platform list).
186 * @return boolean TRUE if RDBMS is supported; otherwise returns FALSE.
188 function supportedPlatform( $platform = NULL ) {
189 return is_object( $this->parent
) ?
$this->parent
->supportedPlatform( $platform ) : TRUE;
193 * Returns the prefix set by the ranking ancestor of the database object.
195 * @param string $name Prefix string.
196 * @return string Prefix.
198 function prefix( $name = '' ) {
199 return is_object( $this->parent
) ?
$this->parent
->prefix( $name ) : $name;
203 * Extracts a field ID from the specified field.
205 * @param string $field Field.
206 * @return string Field ID.
208 function FieldID( $field ) {
209 return strtoupper( preg_replace( '/^`(.+)`$/', '$1', $field ) );
214 * Creates a table object in ADOdb's datadict format
216 * This class stores information about a database table. As charactaristics
217 * of the table are loaded from the external source, methods and properties
218 * of this class are used to build up the table description in ADOdb's
224 class dbTable
extends dbObject
{
227 * @var string Table name
232 * @var array Field specifier: Meta-information about each field
234 var $fields = array();
237 * @var array List of table indexes.
239 var $indexes = array();
242 * @var array Table options: Table-level options
247 * @var string Field index: Keeps track of which field is currently being processed
252 * @var boolean Mark table for destruction
258 * @var boolean Mark field for destruction (not yet implemented)
261 var $drop_field = array();
264 * @var array Platform-specific options
267 var $currentPlatform = true;
271 * Iniitializes a new table object.
273 * @param string $prefix DB Object prefix
274 * @param array $attributes Array of table attributes.
276 function dbTable( &$parent, $attributes = NULL ) {
277 $this->parent
=& $parent;
278 $this->name
= $this->prefix($attributes['NAME']);
282 * XML Callback to process start elements. Elements currently
283 * processed are: INDEX, DROP, FIELD, KEY, NOTNULL, AUTOINCREMENT & DEFAULT.
287 function _tag_open( &$parser, $tag, $attributes ) {
288 $this->currentElement
= strtoupper( $tag );
290 switch( $this->currentElement
) {
292 if( !isset( $attributes['PLATFORM'] ) OR $this->supportedPlatform( $attributes['PLATFORM'] ) ) {
293 xml_set_object( $parser, $this->addIndex( $attributes ) );
297 if( !isset( $attributes['PLATFORM'] ) OR $this->supportedPlatform( $attributes['PLATFORM'] ) ) {
298 xml_set_object( $parser, $this->addData( $attributes ) );
306 $fieldName = $attributes['NAME'];
307 $fieldType = $attributes['TYPE'];
308 $fieldSize = isset( $attributes['SIZE'] ) ?
$attributes['SIZE'] : NULL;
309 $fieldOpts = !empty( $attributes['OPTS'] ) ?
$attributes['OPTS'] : NULL;
311 $this->addField( $fieldName, $fieldType, $fieldSize, $fieldOpts );
315 case 'AUTOINCREMENT':
319 // Add a field option
320 $this->addFieldOpt( $this->current_field
, $this->currentElement
);
323 // Add a field option to the table object
325 // Work around ADOdb datadict issue that misinterprets empty strings.
326 if( $attributes['VALUE'] == '' ) {
327 $attributes['VALUE'] = " '' ";
330 $this->addFieldOpt( $this->current_field
, $this->currentElement
, $attributes['VALUE'] );
334 // Accept platform-specific options
335 $this->currentPlatform
= ( !isset( $attributes['PLATFORM'] ) OR $this->supportedPlatform( $attributes['PLATFORM'] ) );
338 // print_r( array( $tag, $attributes ) );
343 * XML Callback to process CDATA elements
347 function _tag_cdata( &$parser, $cdata ) {
348 switch( $this->currentElement
) {
349 // Table/field constraint
351 if( isset( $this->current_field
) ) {
352 $this->addFieldOpt( $this->current_field
, $this->currentElement
, $cdata );
354 $this->addTableOpt( $cdata );
357 // Table/field option
359 if( isset( $this->current_field
) ) {
360 $this->addFieldOpt( $this->current_field
, $cdata );
362 $this->addTableOpt( $cdata );
371 * XML Callback to process end elements
375 function _tag_close( &$parser, $tag ) {
376 $this->currentElement
= '';
378 switch( strtoupper( $tag ) ) {
380 $this->parent
->addSQL( $this->create( $this->parent
) );
381 xml_set_object( $parser, $this->parent
);
385 unset($this->current_field
);
389 $this->currentPlatform
= true;
397 * Adds an index to a table object
399 * @param array $attributes Index attributes
400 * @return object dbIndex object
402 function &addIndex( $attributes ) {
403 $name = strtoupper( $attributes['NAME'] );
404 $this->indexes
[$name] =& new dbIndex( $this, $attributes );
405 return $this->indexes
[$name];
409 * Adds data to a table object
411 * @param array $attributes Data attributes
412 * @return object dbData object
414 function &addData( $attributes ) {
415 if( !isset( $this->data
) ) {
416 $this->data
=& new dbData( $this, $attributes );
422 * Adds a field to a table object
424 * $name is the name of the table to which the field should be added.
425 * $type is an ADODB datadict field type. The following field types
426 * are supported as of ADODB 3.40:
428 * - X: CLOB (character large object) or largest varchar size
429 * if CLOB is not supported
430 * - C2: Multibyte varchar
431 * - X2: Multibyte CLOB
432 * - B: BLOB (binary large object)
433 * - D: Date (some databases do not support this, and we return a datetime type)
434 * - T: Datetime or Timestamp
435 * - L: Integer field suitable for storing booleans (0 or 1)
436 * - I: Integer (mapped to I4)
437 * - I1: 1-byte integer
438 * - I2: 2-byte integer
439 * - I4: 4-byte integer
440 * - I8: 8-byte integer
441 * - F: Floating point number
442 * - N: Numeric or decimal number
444 * @param string $name Name of the table to which the field will be added.
445 * @param string $type ADODB datadict field type.
446 * @param string $size Field size
447 * @param array $opts Field options array
448 * @return array Field specifier array
450 function addField( $name, $type, $size = NULL, $opts = NULL ) {
451 $field_id = $this->FieldID( $name );
453 // Set the field index so we know where we are
454 $this->current_field
= $field_id;
456 // Set the field name (required)
457 $this->fields
[$field_id]['NAME'] = $name;
459 // Set the field type (required)
460 $this->fields
[$field_id]['TYPE'] = $type;
462 // Set the field size (optional)
463 if( isset( $size ) ) {
464 $this->fields
[$field_id]['SIZE'] = $size;
467 // Set the field options
468 if( isset( $opts ) ) {
469 $this->fields
[$field_id]['OPTS'] = array($opts);
471 $this->fields
[$field_id]['OPTS'] = array();
476 * Adds a field option to the current field specifier
478 * This method adds a field option allowed by the ADOdb datadict
479 * and appends it to the given field.
481 * @param string $field Field name
482 * @param string $opt ADOdb field option
483 * @param mixed $value Field option value
484 * @return array Field specifier array
486 function addFieldOpt( $field, $opt, $value = NULL ) {
487 if( $this->currentPlatform
) {
488 if( !isset( $value ) ) {
489 $this->fields
[$this->FieldID( $field )]['OPTS'][] = $opt;
490 // Add the option and value
492 $this->fields
[$this->FieldID( $field )]['OPTS'][] = array( $opt => $value );
498 * Adds an option to the table
500 * This method takes a comma-separated list of table-level options
501 * and appends them to the table object.
503 * @param string $opt Table option
504 * @return array Options
506 function addTableOpt( $opt ) {
507 if( $this->currentPlatform
) {
508 $this->opts
[] = $opt;
514 * Generates the SQL that will create the table in the database
516 * @param object $xmls adoSchema object
517 * @return array Array containing table creation SQL
519 function create( &$xmls ) {
522 // drop any existing indexes
523 if( is_array( $legacy_indexes = $xmls->dict
->MetaIndexes( $this->name
) ) ) {
524 foreach( $legacy_indexes as $index => $index_details ) {
525 $sql[] = $xmls->dict
->DropIndexSQL( $index, $this->name
);
529 // remove fields to be dropped from table object
530 foreach( $this->drop_field
as $field ) {
531 unset( $this->fields
[$field] );
535 if( is_array( $legacy_fields = $xmls->dict
->MetaColumns( $this->name
) ) ) {
537 if( $this->drop_table
) {
538 $sql[] = $xmls->dict
->DropTableSQL( $this->name
);
543 // drop any existing fields not in schema
544 foreach( $legacy_fields as $field_id => $field ) {
545 if( !isset( $this->fields
[$field_id] ) ) {
546 $sql[] = $xmls->dict
->DropColumnSQL( $this->name
, $field->name
);
549 // if table doesn't exist
551 if( $this->drop_table
) {
555 $legacy_fields = array();
558 // Loop through the field specifier array, building the associative array for the field options
561 foreach( $this->fields
as $field_id => $finfo ) {
562 // Set an empty size if it isn't supplied
563 if( !isset( $finfo['SIZE'] ) ) {
567 // Initialize the field array with the type and size
568 $fldarray[$field_id] = array(
569 'NAME' => $finfo['NAME'],
570 'TYPE' => $finfo['TYPE'],
571 'SIZE' => $finfo['SIZE']
574 // Loop through the options array and add the field options.
575 if( isset( $finfo['OPTS'] ) ) {
576 foreach( $finfo['OPTS'] as $opt ) {
577 // Option has an argument.
578 if( is_array( $opt ) ) {
580 $value = $opt[key( $opt )];
581 @$fldarray[$field_id][$key] .= $value;
582 // Option doesn't have arguments
584 $fldarray[$field_id][$opt] = $opt;
590 if( empty( $legacy_fields ) ) {
591 // Create the new table
592 $sql[] = $xmls->dict
->CreateTableSQL( $this->name
, $fldarray, $this->opts
);
593 logMsg( end( $sql ), 'Generated CreateTableSQL' );
595 // Upgrade an existing table
596 logMsg( "Upgrading {$this->name} using '{$xmls->upgrade}'" );
597 switch( $xmls->upgrade
) {
598 // Use ChangeTableSQL
600 logMsg( 'Generated ChangeTableSQL (ALTERing table)' );
601 $sql[] = $xmls->dict
->ChangeTableSQL( $this->name
, $fldarray, $this->opts
);
604 logMsg( 'Doing upgrade REPLACE (testing)' );
605 $sql[] = $xmls->dict
->DropTableSQL( $this->name
);
606 $sql[] = $xmls->dict
->CreateTableSQL( $this->name
, $fldarray, $this->opts
);
614 foreach( $this->indexes
as $index ) {
615 $sql[] = $index->create( $xmls );
618 if( isset( $this->data
) ) {
619 $sql[] = $this->data
->create( $xmls );
626 * Marks a field or table for destruction
629 if( isset( $this->current_field
) ) {
630 // Drop the current field
631 logMsg( "Dropping field '{$this->current_field}' from table '{$this->name}'" );
632 // $this->drop_field[$this->current_field] = $xmls->dict->DropColumnSQL( $this->name, $this->current_field );
633 $this->drop_field
[$this->current_field
] = $this->current_field
;
635 // Drop the current table
636 logMsg( "Dropping table '{$this->name}'" );
637 // $this->drop_table = $xmls->dict->DropTableSQL( $this->name );
638 $this->drop_table
= TRUE;
644 * Creates an index object in ADOdb's datadict format
646 * This class stores information about a database index. As charactaristics
647 * of the index are loaded from the external source, methods and properties
648 * of this class are used to build up the index description in ADOdb's
654 class dbIndex
extends dbObject
{
657 * @var string Index name
662 * @var array Index options: Index-level options
667 * @var array Indexed fields: Table columns included in this index
669 var $columns = array();
672 * @var boolean Mark index for destruction
678 * Initializes the new dbIndex object.
680 * @param object $parent Parent object
681 * @param array $attributes Attributes
685 function dbIndex( &$parent, $attributes = NULL ) {
686 $this->parent
=& $parent;
688 $this->name
= $this->prefix ($attributes['NAME']);
692 * XML Callback to process start elements
694 * Processes XML opening tags.
695 * Elements currently processed are: DROP, CLUSTERED, BITMAP, UNIQUE, FULLTEXT & HASH.
699 function _tag_open( &$parser, $tag, $attributes ) {
700 $this->currentElement
= strtoupper( $tag );
702 switch( $this->currentElement
) {
712 $this->addIndexOpt( $this->currentElement
);
715 // print_r( array( $tag, $attributes ) );
720 * XML Callback to process CDATA elements
722 * Processes XML cdata.
726 function _tag_cdata( &$parser, $cdata ) {
727 switch( $this->currentElement
) {
730 $this->addField( $cdata );
738 * XML Callback to process end elements
742 function _tag_close( &$parser, $tag ) {
743 $this->currentElement
= '';
745 switch( strtoupper( $tag ) ) {
747 xml_set_object( $parser, $this->parent
);
753 * Adds a field to the index
755 * @param string $name Field name
756 * @return string Field list
758 function addField( $name ) {
759 $this->columns
[$this->FieldID( $name )] = $name;
761 // Return the field list
762 return $this->columns
;
766 * Adds options to the index
768 * @param string $opt Comma-separated list of index options.
769 * @return string Option list
771 function addIndexOpt( $opt ) {
772 $this->opts
[] = $opt;
774 // Return the options list
779 * Generates the SQL that will create the index in the database
781 * @param object $xmls adoSchema object
782 * @return array Array containing index creation SQL
784 function create( &$xmls ) {
789 // eliminate any columns that aren't in the table
790 foreach( $this->columns
as $id => $col ) {
791 if( !isset( $this->parent
->fields
[$id] ) ) {
792 unset( $this->columns
[$id] );
796 return $xmls->dict
->CreateIndexSQL( $this->name
, $this->parent
->name
, $this->columns
, $this->opts
);
800 * Marks an index for destruction
808 * Creates a data object in ADOdb's datadict format
810 * This class stores information about table data, and is called
811 * when we need to load field data into a table.
816 class dbData
extends dbObject
{
823 * Initializes the new dbData object.
825 * @param object $parent Parent object
826 * @param array $attributes Attributes
830 function dbData( &$parent, $attributes = NULL ) {
831 $this->parent
=& $parent;
835 * XML Callback to process start elements
837 * Processes XML opening tags.
838 * Elements currently processed are: ROW and F (field).
842 function _tag_open( &$parser, $tag, $attributes ) {
843 $this->currentElement
= strtoupper( $tag );
845 switch( $this->currentElement
) {
847 $this->row
= count( $this->data
);
848 $this->data
[$this->row
] = array();
851 $this->addField($attributes);
853 // print_r( array( $tag, $attributes ) );
858 * XML Callback to process CDATA elements
860 * Processes XML cdata.
864 function _tag_cdata( &$parser, $cdata ) {
865 switch( $this->currentElement
) {
868 $this->addData( $cdata );
876 * XML Callback to process end elements
880 function _tag_close( &$parser, $tag ) {
881 $this->currentElement
= '';
883 switch( strtoupper( $tag ) ) {
885 xml_set_object( $parser, $this->parent
);
891 * Adds a field to the insert
893 * @param string $name Field name
894 * @return string Field list
896 function addField( $attributes ) {
897 // check we're in a valid row
898 if( !isset( $this->row
) ||
!isset( $this->data
[$this->row
] ) ) {
902 // Set the field index so we know where we are
903 if( isset( $attributes['NAME'] ) ) {
904 $this->current_field
= $this->FieldID( $attributes['NAME'] );
906 $this->current_field
= count( $this->data
[$this->row
] );
910 if( !isset( $this->data
[$this->row
][$this->current_field
] ) ) {
911 $this->data
[$this->row
][$this->current_field
] = '';
916 * Adds options to the index
918 * @param string $opt Comma-separated list of index options.
919 * @return string Option list
921 function addData( $cdata ) {
922 // check we're in a valid field
923 if ( isset( $this->data
[$this->row
][$this->current_field
] ) ) {
925 $this->data
[$this->row
][$this->current_field
] .= $cdata;
930 * Generates the SQL that will add/update the data in the database
932 * @param object $xmls adoSchema object
933 * @return array Array containing index creation SQL
935 function create( &$xmls ) {
936 $table = $xmls->dict
->TableName($this->parent
->name
);
937 $table_field_count = count($this->parent
->fields
);
938 $tables = $xmls->db
->MetaTables();
941 $ukeys = $xmls->db
->MetaPrimaryKeys( $table );
942 if( !empty( $this->parent
->indexes
) and !empty( $ukeys ) ) {
943 foreach( $this->parent
->indexes
as $indexObj ) {
944 if( !in_array( $indexObj->name
, $ukeys ) ) $ukeys[] = $indexObj->name
;
948 // eliminate any columns that aren't in the table
949 foreach( $this->data
as $row ) {
950 $table_fields = $this->parent
->fields
;
952 $rawfields = array(); // Need to keep some of the unprocessed data on hand.
954 foreach( $row as $field_id => $field_data ) {
955 if( !array_key_exists( $field_id, $table_fields ) ) {
956 if( is_numeric( $field_id ) ) {
957 $field_id = reset( array_keys( $table_fields ) );
963 $name = $table_fields[$field_id]['NAME'];
965 switch( $table_fields[$field_id]['TYPE'] ) {
971 $fields[$name] = intval($field_data);
978 $fields[$name] = $xmls->db
->qstr( $field_data );
979 $rawfields[$name] = $field_data;
982 unset($table_fields[$field_id]);
986 // check that at least 1 column is specified
987 if( empty( $fields ) ) {
991 // check that no required columns are missing
992 if( count( $fields ) < $table_field_count ) {
993 foreach( $table_fields as $field ) {
994 if( isset( $field['OPTS'] ) and ( in_array( 'NOTNULL', $field['OPTS'] ) ||
in_array( 'KEY', $field['OPTS'] ) ) && !in_array( 'AUTOINCREMENT', $field['OPTS'] ) ) {
1000 // The rest of this method deals with updating existing data records.
1002 if( !in_array( $table, $tables ) or ( $mode = $xmls->existingData() ) == XMLS_MODE_INSERT
) {
1003 // Table doesn't yet exist, so it's safe to insert.
1004 logMsg( "$table doesn't exist, inserting or mode is INSERT" );
1005 $sql[] = 'INSERT INTO '. $table .' ('. implode( ',', array_keys( $fields ) ) .') VALUES ('. implode( ',', $fields ) .')';
1009 // Prepare to test for potential violations. Get primary keys and unique indexes
1010 $mfields = array_merge( $fields, $rawfields );
1011 $keyFields = array_intersect( $ukeys, array_keys( $mfields ) );
1013 if( empty( $ukeys ) or count( $keyFields ) == 0 ) {
1014 // No unique keys in schema, so safe to insert
1015 logMsg( "Either schema or data has no unique keys, so safe to insert" );
1016 $sql[] = 'INSERT INTO '. $table .' ('. implode( ',', array_keys( $fields ) ) .') VALUES ('. implode( ',', $fields ) .')';
1020 // Select record containing matching unique keys.
1022 foreach( $ukeys as $key ) {
1023 if( isset( $mfields[$key] ) and $mfields[$key] ) {
1024 if( $where ) $where .= ' AND ';
1025 $where .= $key . ' = ' . $xmls->db
->qstr( $mfields[$key] );
1028 $records = $xmls->db
->Execute( 'SELECT * FROM ' . $table . ' WHERE ' . $where );
1029 switch( $records->RecordCount() ) {
1031 // No matching record, so safe to insert.
1032 logMsg( "No matching records. Inserting new row with unique data" );
1033 $sql[] = $xmls->db
->GetInsertSQL( $records, $mfields );
1036 // Exactly one matching record, so we can update if the mode permits.
1037 logMsg( "One matching record..." );
1038 if( $mode == XMLS_MODE_UPDATE
) {
1039 logMsg( "...Updating existing row from unique data" );
1040 $sql[] = $xmls->db
->GetUpdateSQL( $records, $mfields );
1044 // More than one matching record; the result is ambiguous, so we must ignore the row.
1045 logMsg( "More than one matching record. Ignoring row." );
1053 * Creates the SQL to execute a list of provided SQL queries
1058 class dbQuerySet
extends dbObject
{
1061 * @var array List of SQL queries
1063 var $queries = array();
1066 * @var string String used to build of a query line by line
1071 * @var string Query prefix key
1073 var $prefixKey = '';
1076 * @var boolean Auto prefix enable (TRUE)
1078 var $prefixMethod = 'AUTO';
1081 * Initializes the query set.
1083 * @param object $parent Parent object
1084 * @param array $attributes Attributes
1086 function dbQuerySet( &$parent, $attributes = NULL ) {
1087 $this->parent
=& $parent;
1089 // Overrides the manual prefix key
1090 if( isset( $attributes['KEY'] ) ) {
1091 $this->prefixKey
= $attributes['KEY'];
1094 $prefixMethod = isset( $attributes['PREFIXMETHOD'] ) ?
strtoupper( trim( $attributes['PREFIXMETHOD'] ) ) : '';
1096 // Enables or disables automatic prefix prepending
1097 switch( $prefixMethod ) {
1099 $this->prefixMethod
= 'AUTO';
1102 $this->prefixMethod
= 'MANUAL';
1105 $this->prefixMethod
= 'NONE';
1111 * XML Callback to process start elements. Elements currently
1112 * processed are: QUERY.
1116 function _tag_open( &$parser, $tag, $attributes ) {
1117 $this->currentElement
= strtoupper( $tag );
1119 switch( $this->currentElement
) {
1121 // Create a new query in a SQL queryset.
1122 // Ignore this query set if a platform is specified and it's different than the
1123 // current connection platform.
1124 if( !isset( $attributes['PLATFORM'] ) OR $this->supportedPlatform( $attributes['PLATFORM'] ) ) {
1127 $this->discardQuery();
1131 // print_r( array( $tag, $attributes ) );
1136 * XML Callback to process CDATA elements
1138 function _tag_cdata( &$parser, $cdata ) {
1139 switch( $this->currentElement
) {
1140 // Line of queryset SQL data
1142 $this->buildQuery( $cdata );
1150 * XML Callback to process end elements
1154 function _tag_close( &$parser, $tag ) {
1155 $this->currentElement
= '';
1157 switch( strtoupper( $tag ) ) {
1159 // Add the finished query to the open query set.
1163 $this->parent
->addSQL( $this->create( $this->parent
) );
1164 xml_set_object( $parser, $this->parent
);
1173 * Re-initializes the query.
1175 * @return boolean TRUE
1177 function newQuery() {
1184 * Discards the existing query.
1186 * @return boolean TRUE
1188 function discardQuery() {
1189 unset( $this->query
);
1195 * Appends a line to a query that is being built line by line
1197 * @param string $data Line of SQL data or NULL to initialize a new query
1198 * @return string SQL query string.
1200 function buildQuery( $sql = NULL ) {
1201 if( !isset( $this->query
) OR empty( $sql ) ) {
1205 $this->query
.= $sql;
1207 return $this->query
;
1211 * Adds a completed query to the query list
1213 * @return string SQL of added query
1215 function addQuery() {
1216 if( !isset( $this->query
) ) {
1220 $this->queries
[] = $return = trim($this->query
);
1222 unset( $this->query
);
1228 * Creates and returns the current query set
1230 * @param object $xmls adoSchema object
1231 * @return array Query set
1233 function create( &$xmls ) {
1234 foreach( $this->queries
as $id => $query ) {
1235 switch( $this->prefixMethod
) {
1237 // Enable auto prefix replacement
1239 // Process object prefix.
1240 // Evaluate SQL statements to prepend prefix to objects
1241 $query = $this->prefixQuery( '/^\s*((?is)INSERT\s+(INTO\s+)?)((\w+\s*,?\s*)+)(\s.*$)/', $query, $xmls->objectPrefix
);
1242 $query = $this->prefixQuery( '/^\s*((?is)UPDATE\s+(FROM\s+)?)((\w+\s*,?\s*)+)(\s.*$)/', $query, $xmls->objectPrefix
);
1243 $query = $this->prefixQuery( '/^\s*((?is)DELETE\s+(FROM\s+)?)((\w+\s*,?\s*)+)(\s.*$)/', $query, $xmls->objectPrefix
);
1245 // SELECT statements aren't working yet
1246 #$data = preg_replace( '/(?ias)(^\s*SELECT\s+.*\s+FROM)\s+(\W\s*,?\s*)+((?i)\s+WHERE.*$)/', "\1 $prefix\2 \3", $data );
1249 // If prefixKey is set and has a value then we use it to override the default constant XMLS_PREFIX.
1250 // If prefixKey is not set, we use the default constant XMLS_PREFIX
1251 if( isset( $this->prefixKey
) AND( $this->prefixKey
!== '' ) ) {
1252 // Enable prefix override
1253 $query = str_replace( $this->prefixKey
, $xmls->objectPrefix
, $query );
1255 // Use default replacement
1256 $query = str_replace( XMLS_PREFIX
, $xmls->objectPrefix
, $query );
1260 $this->queries
[$id] = trim( $query );
1263 // Return the query set array
1264 return $this->queries
;
1268 * Rebuilds the query with the prefix attached to any objects
1270 * @param string $regex Regex used to add prefix
1271 * @param string $query SQL query string
1272 * @param string $prefix Prefix to be appended to tables, indices, etc.
1273 * @return string Prefixed SQL query string.
1275 function prefixQuery( $regex, $query, $prefix = NULL ) {
1276 if( !isset( $prefix ) ) {
1280 if( preg_match( $regex, $query, $match ) ) {
1281 $preamble = $match[1];
1282 $postamble = $match[5];
1283 $objectList = explode( ',', $match[3] );
1284 // $prefix = $prefix . '_';
1288 foreach( $objectList as $object ) {
1289 if( $prefixedList !== '' ) {
1290 $prefixedList .= ', ';
1293 $prefixedList .= $prefix . trim( $object );
1296 $query = $preamble . ' ' . $prefixedList . ' ' . $postamble;
1304 * Loads and parses an XML file, creating an array of "ready-to-run" SQL statements
1306 * This class is used to load and parse the XML file, to create an array of SQL statements
1307 * that can be used to build a database, and to build the database using the SQL array.
1309 * @tutorial getting_started.pkg
1311 * @author Richard Tango-Lowy & Dan Cech
1312 * @version $Revision$
1319 * @var array Array containing SQL queries to generate all objects
1325 * @var object ADOdb connection object
1331 * @var object ADOdb Data Dictionary
1337 * @var string Current XML element
1340 var $currentElement = '';
1343 * @var string If set (to 'ALTER' or 'REPLACE'), upgrade an existing database
1349 * @var string Optional object prefix
1352 var $objectPrefix = '';
1355 * @var long Original Magic Quotes Runtime value
1361 * @var long System debug
1367 * @var string Regular expression to find schema version
1370 var $versionRegex = '/<schema.*?( version="([^"]*)")?.*?>/';
1373 * @var string Current schema version
1379 * @var int Success of last Schema execution
1384 * @var bool Execute SQL inline as it is generated
1389 * @var bool Continue SQL execution if errors occur
1391 var $continueOnError;
1394 * @var int How to handle existing data rows (insert, update, or ignore)
1399 * Creates an adoSchema object
1401 * Creating an adoSchema object is the first step in processing an XML schema.
1402 * The only parameter is an ADOdb database connection object, which must already
1403 * have been created.
1405 * @param object $db ADOdb database connection object.
1407 function adoSchema( &$db ) {
1408 // Initialize the environment
1409 $this->mgq
= get_magic_quotes_runtime();
1410 set_magic_quotes_runtime(0);
1413 $this->debug
= $this->db
->debug
;
1414 $this->dict
= NewDataDictionary( $this->db
);
1415 $this->sqlArray
= array();
1416 $this->schemaVersion
= XMLS_SCHEMA_VERSION
;
1417 $this->executeInline( XMLS_EXECUTE_INLINE
);
1418 $this->continueOnError( XMLS_CONTINUE_ON_ERROR
);
1419 $this->existingData( XMLS_EXISTING_DATA
);
1420 $this->setUpgradeMethod();
1424 * Sets the method to be used for upgrading an existing database
1426 * Use this method to specify how existing database objects should be upgraded.
1427 * The method option can be set to ALTER, REPLACE, BEST, or NONE. ALTER attempts to
1428 * alter each database object directly, REPLACE attempts to rebuild each object
1429 * from scratch, BEST attempts to determine the best upgrade method for each
1430 * object, and NONE disables upgrading.
1432 * This method is not yet used by AXMLS, but exists for backward compatibility.
1433 * The ALTER method is automatically assumed when the adoSchema object is
1434 * instantiated; other upgrade methods are not currently supported.
1436 * @param string $method Upgrade method (ALTER|REPLACE|BEST|NONE)
1437 * @returns string Upgrade method used
1439 function SetUpgradeMethod( $method = '' ) {
1440 if( !is_string( $method ) ) {
1444 $method = strtoupper( $method );
1446 // Handle the upgrade methods
1449 $this->upgrade
= $method;
1452 $this->upgrade
= $method;
1455 $this->upgrade
= 'ALTER';
1458 $this->upgrade
= 'NONE';
1461 // Use default if no legitimate method is passed.
1462 $this->upgrade
= XMLS_DEFAULT_UPGRADE_METHOD
;
1465 return $this->upgrade
;
1469 * Specifies how to handle existing data row when there is a unique key conflict.
1471 * The existingData setting specifies how the parser should handle existing rows
1472 * when a unique key violation occurs during the insert. This can happen when inserting
1473 * data into an existing table with one or more primary keys or unique indexes.
1474 * The existingData method takes one of three options: XMLS_MODE_INSERT attempts
1475 * to always insert the data as a new row. In the event of a unique key violation,
1476 * the database will generate an error. XMLS_MODE_UPDATE attempts to update the
1477 * any existing rows with the new data based upon primary or unique key fields in
1478 * the schema. If the data row in the schema specifies no unique fields, the row
1479 * data will be inserted as a new row. XMLS_MODE_IGNORE specifies that any data rows
1480 * that would result in a unique key violation be ignored; no inserts or updates will
1481 * take place. For backward compatibility, the default setting is XMLS_MODE_INSERT,
1482 * but XMLS_MODE_UPDATE will generally be the most appropriate setting.
1484 * @param int $mode XMLS_MODE_INSERT, XMLS_MODE_UPDATE, or XMLS_MODE_IGNORE
1485 * @return int current mode
1487 function ExistingData( $mode = NULL ) {
1488 if( is_int( $mode ) ) {
1490 case XMLS_MODE_UPDATE
:
1491 $mode = XMLS_MODE_UPDATE
;
1493 case XMLS_MODE_IGNORE
:
1494 $mode = XMLS_MODE_IGNORE
;
1496 case XMLS_MODE_INSERT
:
1497 $mode = XMLS_MODE_INSERT
;
1500 $mode = XMLS_EXISITNG_DATA
;
1503 $this->existingData
= $mode;
1506 return $this->existingData
;
1510 * Enables/disables inline SQL execution.
1512 * Call this method to enable or disable inline execution of the schema. If the mode is set to TRUE (inline execution),
1513 * AXMLS applies the SQL to the database immediately as each schema entity is parsed. If the mode
1514 * is set to FALSE (post execution), AXMLS parses the entire schema and you will need to call adoSchema::ExecuteSchema()
1515 * to apply the schema to the database.
1517 * @param bool $mode execute
1518 * @return bool current execution mode
1520 * @see ParseSchema(), ExecuteSchema()
1522 function ExecuteInline( $mode = NULL ) {
1523 if( is_bool( $mode ) ) {
1524 $this->executeInline
= $mode;
1527 return $this->executeInline
;
1531 * Enables/disables SQL continue on error.
1533 * Call this method to enable or disable continuation of SQL execution if an error occurs.
1534 * If the mode is set to TRUE (continue), AXMLS will continue to apply SQL to the database, even if an error occurs.
1535 * If the mode is set to FALSE (halt), AXMLS will halt execution of generated sql if an error occurs, though parsing
1536 * of the schema will continue.
1538 * @param bool $mode execute
1539 * @return bool current continueOnError mode
1541 * @see addSQL(), ExecuteSchema()
1543 function ContinueOnError( $mode = NULL ) {
1544 if( is_bool( $mode ) ) {
1545 $this->continueOnError
= $mode;
1548 return $this->continueOnError
;
1552 * Loads an XML schema from a file and converts it to SQL.
1554 * Call this method to load the specified schema (see the DTD for the proper format) from
1555 * the filesystem and generate the SQL necessary to create the database
1556 * described. This method automatically converts the schema to the latest
1557 * axmls schema version.
1558 * @see ParseSchemaString()
1560 * @param string $file Name of XML schema file.
1561 * @param bool $returnSchema Return schema rather than parsing.
1562 * @return array Array of SQL queries, ready to execute
1564 function ParseSchema( $filename, $returnSchema = FALSE ) {
1565 return $this->ParseSchemaString( $this->ConvertSchemaFile( $filename ), $returnSchema );
1569 * Loads an XML schema from a file and converts it to SQL.
1571 * Call this method to load the specified schema directly from a file (see
1572 * the DTD for the proper format) and generate the SQL necessary to create
1573 * the database described by the schema. Use this method when you are dealing
1574 * with large schema files. Otherwise, ParseSchema() is faster.
1575 * This method does not automatically convert the schema to the latest axmls
1576 * schema version. You must convert the schema manually using either the
1577 * ConvertSchemaFile() or ConvertSchemaString() method.
1578 * @see ParseSchema()
1579 * @see ConvertSchemaFile()
1580 * @see ConvertSchemaString()
1582 * @param string $file Name of XML schema file.
1583 * @param bool $returnSchema Return schema rather than parsing.
1584 * @return array Array of SQL queries, ready to execute.
1586 * @deprecated Replaced by adoSchema::ParseSchema() and adoSchema::ParseSchemaString()
1587 * @see ParseSchema(), ParseSchemaString()
1589 function ParseSchemaFile( $filename, $returnSchema = FALSE ) {
1591 if( !($fp = fopen( $filename, 'r' )) ) {
1592 logMsg( 'Unable to open file' );
1596 // do version detection here
1597 if( $this->SchemaFileVersion( $filename ) != $this->schemaVersion
) {
1598 logMsg( 'Invalid Schema Version' );
1602 if( $returnSchema ) {
1604 while( $data = fread( $fp, 4096 ) ) {
1605 $xmlstring .= $data . "\n";
1612 $xmlParser = $this->create_parser();
1615 while( $data = fread( $fp, 4096 ) ) {
1616 if( !xml_parse( $xmlParser, $data, feof( $fp ) ) ) {
1618 "XML error: %s at line %d",
1619 xml_error_string( xml_get_error_code( $xmlParser) ),
1620 xml_get_current_line_number( $xmlParser)
1625 xml_parser_free( $xmlParser );
1627 return $this->sqlArray
;
1631 * Converts an XML schema string to SQL.
1633 * Call this method to parse a string containing an XML schema (see the DTD for the proper format)
1634 * and generate the SQL necessary to create the database described by the schema.
1635 * @see ParseSchema()
1637 * @param string $xmlstring XML schema string.
1638 * @param bool $returnSchema Return schema rather than parsing.
1639 * @return array Array of SQL queries, ready to execute.
1641 function ParseSchemaString( $xmlstring, $returnSchema = FALSE ) {
1642 if( !is_string( $xmlstring ) OR empty( $xmlstring ) ) {
1643 logMsg( 'Empty or Invalid Schema' );
1647 // do version detection here
1648 if( $this->SchemaStringVersion( $xmlstring ) != $this->schemaVersion
) {
1649 logMsg( 'Invalid Schema Version' );
1653 if( $returnSchema ) {
1659 $xmlParser = $this->create_parser();
1661 if( !xml_parse( $xmlParser, $xmlstring, TRUE ) ) {
1663 "XML error: %s at line %d",
1664 xml_error_string( xml_get_error_code( $xmlParser) ),
1665 xml_get_current_line_number( $xmlParser)
1669 xml_parser_free( $xmlParser );
1671 return $this->sqlArray
;
1675 * Loads an XML schema from a file and converts it to uninstallation SQL.
1677 * Call this method to load the specified schema (see the DTD for the proper format) from
1678 * the filesystem and generate the SQL necessary to remove the database described.
1679 * @see RemoveSchemaString()
1681 * @param string $file Name of XML schema file.
1682 * @param bool $returnSchema Return schema rather than parsing.
1683 * @return array Array of SQL queries, ready to execute
1685 function RemoveSchema( $filename, $returnSchema = FALSE ) {
1686 return $this->RemoveSchemaString( $this->ConvertSchemaFile( $filename ), $returnSchema );
1690 * Converts an XML schema string to uninstallation SQL.
1692 * Call this method to parse a string containing an XML schema (see the DTD for the proper format)
1693 * and generate the SQL necessary to uninstall the database described by the schema.
1694 * @see RemoveSchema()
1696 * @param string $schema XML schema string.
1697 * @param bool $returnSchema Return schema rather than parsing.
1698 * @return array Array of SQL queries, ready to execute.
1700 function RemoveSchemaString( $schema, $returnSchema = FALSE ) {
1702 // grab current version
1703 if( !( $version = $this->SchemaStringVersion( $schema ) ) ) {
1707 return $this->ParseSchemaString( $this->TransformSchema( $schema, 'remove-' . $version), $returnSchema );
1711 * Applies the current XML schema to the database (post execution).
1713 * Call this method to apply the current schema (generally created by calling
1714 * ParseSchema() or ParseSchemaString() ) to the database (creating the tables, indexes,
1715 * and executing other SQL specified in the schema) after parsing.
1716 * @see ParseSchema(), ParseSchemaString(), ExecuteInline()
1718 * @param array $sqlArray Array of SQL statements that will be applied rather than
1719 * the current schema.
1720 * @param boolean $continueOnErr Continue to apply the schema even if an error occurs.
1721 * @returns integer 0 if failure, 1 if errors, 2 if successful.
1723 function ExecuteSchema( $sqlArray = NULL, $continueOnErr = NULL ) {
1724 if( !is_bool( $continueOnErr ) ) {
1725 $continueOnErr = $this->ContinueOnError();
1728 if( !isset( $sqlArray ) ) {
1729 $sqlArray = $this->sqlArray
;
1732 if( !is_array( $sqlArray ) ) {
1735 $this->success
= $this->dict
->ExecuteSQLArray( $sqlArray, $continueOnErr );
1738 return $this->success
;
1742 * Returns the current SQL array.
1744 * Call this method to fetch the array of SQL queries resulting from
1745 * ParseSchema() or ParseSchemaString().
1747 * @param string $format Format: HTML, TEXT, or NONE (PHP array)
1748 * @return array Array of SQL statements or FALSE if an error occurs
1750 function PrintSQL( $format = 'NONE' ) {
1752 return $this->getSQL( $format, $sqlArray );
1756 * Saves the current SQL array to the local filesystem as a list of SQL queries.
1758 * Call this method to save the array of SQL queries (generally resulting from a
1759 * parsed XML schema) to the filesystem.
1761 * @param string $filename Path and name where the file should be saved.
1762 * @return boolean TRUE if save is successful, else FALSE.
1764 function SaveSQL( $filename = './schema.sql' ) {
1766 if( !isset( $sqlArray ) ) {
1767 $sqlArray = $this->sqlArray
;
1769 if( !isset( $sqlArray ) ) {
1773 $fp = fopen( $filename, "w" );
1775 foreach( $sqlArray as $key => $query ) {
1776 fwrite( $fp, $query . ";\n" );
1782 * Create an xml parser
1784 * @return object PHP XML parser object
1788 function &create_parser() {
1789 // Create the parser
1790 $xmlParser = xml_parser_create();
1791 xml_set_object( $xmlParser, $this );
1793 // Initialize the XML callback functions
1794 xml_set_element_handler( $xmlParser, '_tag_open', '_tag_close' );
1795 xml_set_character_data_handler( $xmlParser, '_tag_cdata' );
1801 * XML Callback to process start elements
1805 function _tag_open( &$parser, $tag, $attributes ) {
1806 switch( strtoupper( $tag ) ) {
1808 if( !isset( $attributes['PLATFORM'] ) OR $this->supportedPlatform( $attributes['PLATFORM'] ) ) {
1809 $this->obj
= new dbTable( $this, $attributes );
1810 xml_set_object( $parser, $this->obj
);
1814 if( !isset( $attributes['PLATFORM'] ) OR $this->supportedPlatform( $attributes['PLATFORM'] ) ) {
1815 $this->obj
= new dbQuerySet( $this, $attributes );
1816 xml_set_object( $parser, $this->obj
);
1820 // print_r( array( $tag, $attributes ) );
1826 * XML Callback to process CDATA elements
1830 function _tag_cdata( &$parser, $cdata ) {
1834 * XML Callback to process end elements
1839 function _tag_close( &$parser, $tag ) {
1844 * Converts an XML schema string to the specified DTD version.
1846 * Call this method to convert a string containing an XML schema to a different AXMLS
1847 * DTD version. For instance, to convert a schema created for an pre-1.0 version for
1848 * AXMLS (DTD version 0.1) to a newer version of the DTD (e.g. 0.2). If no DTD version
1849 * parameter is specified, the schema will be converted to the current DTD version.
1850 * If the newFile parameter is provided, the converted schema will be written to the specified
1852 * @see ConvertSchemaFile()
1854 * @param string $schema String containing XML schema that will be converted.
1855 * @param string $newVersion DTD version to convert to.
1856 * @param string $newFile File name of (converted) output file.
1857 * @return string Converted XML schema or FALSE if an error occurs.
1859 function ConvertSchemaString( $schema, $newVersion = NULL, $newFile = NULL ) {
1861 // grab current version
1862 if( !( $version = $this->SchemaStringVersion( $schema ) ) ) {
1866 if( !isset ($newVersion) ) {
1867 $newVersion = $this->schemaVersion
;
1870 if( $version == $newVersion ) {
1873 $result = $this->TransformSchema( $schema, 'convert-' . $version . '-' . $newVersion);
1876 if( is_string( $result ) AND is_string( $newFile ) AND ( $fp = fopen( $newFile, 'w' ) ) ) {
1877 fwrite( $fp, $result );
1885 // compat for pre-4.3 - jlim
1886 function _file_get_contents($path)
1888 if (function_exists('file_get_contents')) return file_get_contents($path);
1889 return join('',file($path));
1893 * Converts an XML schema file to the specified DTD version.
1895 * Call this method to convert the specified XML schema file to a different AXMLS
1896 * DTD version. For instance, to convert a schema created for an pre-1.0 version for
1897 * AXMLS (DTD version 0.1) to a newer version of the DTD (e.g. 0.2). If no DTD version
1898 * parameter is specified, the schema will be converted to the current DTD version.
1899 * If the newFile parameter is provided, the converted schema will be written to the specified
1901 * @see ConvertSchemaString()
1903 * @param string $filename Name of XML schema file that will be converted.
1904 * @param string $newVersion DTD version to convert to.
1905 * @param string $newFile File name of (converted) output file.
1906 * @return string Converted XML schema or FALSE if an error occurs.
1908 function ConvertSchemaFile( $filename, $newVersion = NULL, $newFile = NULL ) {
1910 // grab current version
1911 if( !( $version = $this->SchemaFileVersion( $filename ) ) ) {
1915 if( !isset ($newVersion) ) {
1916 $newVersion = $this->schemaVersion
;
1919 if( $version == $newVersion ) {
1920 $result = _file_get_contents( $filename );
1922 // remove unicode BOM if present
1923 if( substr( $result, 0, 3 ) == sprintf( '%c%c%c', 239, 187, 191 ) ) {
1924 $result = substr( $result, 3 );
1927 $result = $this->TransformSchema( $filename, 'convert-' . $version . '-' . $newVersion, 'file' );
1930 if( is_string( $result ) AND is_string( $newFile ) AND ( $fp = fopen( $newFile, 'w' ) ) ) {
1931 fwrite( $fp, $result );
1938 function TransformSchema( $schema, $xsl, $schematype='string' )
1940 // Fail if XSLT extension is not available
1941 if( ! function_exists( 'xslt_create' ) ) {
1945 $xsl_file = dirname( __FILE__
) . '/xsl/' . $xsl . '.xsl';
1948 if( !is_readable( $xsl_file ) ) {
1952 switch( $schematype )
1955 if( !is_readable( $schema ) ) {
1959 $schema = _file_get_contents( $schema );
1963 if( !is_string( $schema ) ) {
1968 $arguments = array (
1970 '/_xsl' => _file_get_contents( $xsl_file )
1973 // create an XSLT processor
1974 $xh = xslt_create ();
1976 // set error handler
1977 xslt_set_error_handler ($xh, array (&$this, 'xslt_error_handler'));
1979 // process the schema
1980 $result = xslt_process ($xh, 'arg:/_xml', 'arg:/_xsl', NULL, $arguments);
1988 * Processes XSLT transformation errors
1990 * @param object $parser XML parser object
1991 * @param integer $errno Error number
1992 * @param integer $level Error level
1993 * @param array $fields Error information fields
1997 function xslt_error_handler( $parser, $errno, $level, $fields ) {
1998 if( is_array( $fields ) ) {
2000 'Message Type' => ucfirst( $fields['msgtype'] ),
2001 'Message Code' => $fields['code'],
2002 'Message' => $fields['msg'],
2003 'Error Number' => $errno,
2007 switch( $fields['URI'] ) {
2009 $msg['Input'] = 'XML';
2012 $msg['Input'] = 'XSL';
2015 $msg['Input'] = $fields['URI'];
2018 $msg['Line'] = $fields['line'];
2021 'Message Type' => 'Error',
2022 'Error Number' => $errno,
2024 'Fields' => var_export( $fields, TRUE )
2028 $error_details = $msg['Message Type'] . ' in XSLT Transformation' . "\n"
2031 foreach( $msg as $label => $details ) {
2032 $error_details .= '<tr><td><b>' . $label . ': </b></td><td>' . htmlentities( $details ) . '</td></tr>' . "\n";
2035 $error_details .= '</table>';
2037 trigger_error( $error_details, E_USER_ERROR
);
2041 * Returns the AXMLS Schema Version of the requested XML schema file.
2043 * Call this method to obtain the AXMLS DTD version of the requested XML schema file.
2044 * @see SchemaStringVersion()
2046 * @param string $filename AXMLS schema file
2047 * @return string Schema version number or FALSE on error
2049 function SchemaFileVersion( $filename ) {
2051 if( !($fp = fopen( $filename, 'r' )) ) {
2052 // die( 'Unable to open file' );
2057 while( $data = fread( $fp, 4096 ) ) {
2058 if( preg_match( $this->versionRegex
, $data, $matches ) ) {
2059 return !empty( $matches[2] ) ?
$matches[2] : XMLS_DEFAULT_SCHEMA_VERSION
;
2067 * Returns the AXMLS Schema Version of the provided XML schema string.
2069 * Call this method to obtain the AXMLS DTD version of the provided XML schema string.
2070 * @see SchemaFileVersion()
2072 * @param string $xmlstring XML schema string
2073 * @return string Schema version number or FALSE on error
2075 function SchemaStringVersion( $xmlstring ) {
2076 if( !is_string( $xmlstring ) OR empty( $xmlstring ) ) {
2080 if( preg_match( $this->versionRegex
, $xmlstring, $matches ) ) {
2081 return !empty( $matches[2] ) ?
$matches[2] : XMLS_DEFAULT_SCHEMA_VERSION
;
2088 * Extracts an XML schema from an existing database.
2090 * Call this method to create an XML schema string from an existing database.
2091 * If the data parameter is set to TRUE, AXMLS will include the data from the database
2094 * @param boolean $data Include data in schema dump
2095 * @indent string indentation to use
2096 * @prefix string extract only tables with given prefix
2097 * @stripprefix strip prefix string when storing in XML schema
2098 * @return string Generated XML schema
2100 function ExtractSchema( $data = FALSE, $indent = ' ', $prefix = '' , $stripprefix=false) {
2101 $old_mode = $this->db
->SetFetchMode( ADODB_FETCH_NUM
);
2103 $schema = '<?xml version="1.0"?>' . "\n"
2104 . '<schema version="' . $this->schemaVersion
. '">' . "\n";
2106 if( is_array( $tables = $this->db
->MetaTables( 'TABLES' , ($prefix) ?
$prefix.'%' : '') ) ) {
2107 foreach( $tables as $table ) {
2108 if ($stripprefix) $table = str_replace(str_replace('\\_', '_', $pfx ), '', $table);
2109 $schema .= $indent . '<table name="' . htmlentities( $table ) . '">' . "\n";
2111 // grab details from database
2112 $rs = $this->db
->Execute( 'SELECT * FROM ' . $table . ' WHERE -1' );
2113 $fields = $this->db
->MetaColumns( $table );
2114 $indexes = $this->db
->MetaIndexes( $table );
2116 if( is_array( $fields ) ) {
2117 foreach( $fields as $details ) {
2121 if( isset($details->max_length
) && $details->max_length
> 0 ) {
2122 $extra .= ' size="' . $details->max_length
. '"';
2125 if( isset($details->primary_key
) && $details->primary_key
) {
2126 $content[] = '<KEY/>';
2127 } elseif( isset($details->not_null
) && $details->not_null
) {
2128 $content[] = '<NOTNULL/>';
2131 if( isset($details->has_default
) && $details->has_default
) {
2132 $content[] = '<DEFAULT value="' . htmlentities( $details->default_value
) . '"/>';
2135 if( isset($details->auto_increment
) && $details->auto_increment
) {
2136 $content[] = '<AUTOINCREMENT/>';
2139 if( isset($details->unsigned
) && $details->unsigned
) {
2140 $content[] = '<UNSIGNED/>';
2143 // this stops the creation of 'R' columns,
2144 // AUTOINCREMENT is used to create auto columns
2145 $details->primary_key
= 0;
2146 $type = $rs->MetaType( $details );
2148 $schema .= str_repeat( $indent, 2 ) . '<field name="' . htmlentities( $details->name
) . '" type="' . $type . '"' . $extra;
2150 if( !empty( $content ) ) {
2151 $schema .= ">\n" . str_repeat( $indent, 3 )
2152 . implode( "\n" . str_repeat( $indent, 3 ), $content ) . "\n"
2153 . str_repeat( $indent, 2 ) . '</field>' . "\n";
2160 if( is_array( $indexes ) ) {
2161 foreach( $indexes as $index => $details ) {
2162 $schema .= str_repeat( $indent, 2 ) . '<index name="' . $index . '">' . "\n";
2164 if( $details['unique'] ) {
2165 $schema .= str_repeat( $indent, 3 ) . '<UNIQUE/>' . "\n";
2168 foreach( $details['columns'] as $column ) {
2169 $schema .= str_repeat( $indent, 3 ) . '<col>' . htmlentities( $column ) . '</col>' . "\n";
2172 $schema .= str_repeat( $indent, 2 ) . '</index>' . "\n";
2177 $rs = $this->db
->Execute( 'SELECT * FROM ' . $table );
2179 if( is_object( $rs ) && !$rs->EOF
) {
2180 $schema .= str_repeat( $indent, 2 ) . "<data>\n";
2182 while( $row = $rs->FetchRow() ) {
2183 foreach( $row as $key => $val ) {
2184 if ( $val != htmlentities( $val ) ) {
2185 $row[$key] = '<![CDATA[' . $val . ']]>';
2189 $schema .= str_repeat( $indent, 3 ) . '<row><f>' . implode( '</f><f>', $row ) . "</f></row>\n";
2192 $schema .= str_repeat( $indent, 2 ) . "</data>\n";
2196 $schema .= $indent . "</table>\n";
2200 $this->db
->SetFetchMode( $old_mode );
2202 $schema .= '</schema>';
2207 * Sets a prefix for database objects
2209 * Call this method to set a standard prefix that will be prepended to all database tables
2210 * and indices when the schema is parsed. Calling setPrefix with no arguments clears the prefix.
2212 * @param string $prefix Prefix that will be prepended.
2213 * @param boolean $underscore If TRUE, automatically append an underscore character to the prefix.
2214 * @return boolean TRUE if successful, else FALSE
2216 function SetPrefix( $prefix = '', $underscore = TRUE ) {
2219 case empty( $prefix ):
2220 logMsg( 'Cleared prefix' );
2221 $this->objectPrefix
= '';
2224 case strlen( $prefix ) > XMLS_PREFIX_MAXLEN
:
2225 // prefix contains invalid characters
2226 case !preg_match( '/^[a-z][a-z0-9_]+$/i', $prefix ):
2227 logMsg( 'Invalid prefix: ' . $prefix );
2231 if( $underscore AND substr( $prefix, -1 ) != '_' ) {
2236 logMsg( 'Set prefix: ' . $prefix );
2237 $this->objectPrefix
= $prefix;
2242 * Returns an object name with the current prefix prepended.
2244 * @param string $name Name
2245 * @return string Prefixed name
2249 function prefix( $name = '' ) {
2251 if( !empty( $this->objectPrefix
) ) {
2252 // Prepend the object prefix to the table name
2253 // prepend after quote if used
2254 return preg_replace( '/^(`?)(.+)$/', '$1' . $this->objectPrefix
. '$2', $name );
2257 // No prefix set. Use name provided.
2262 * Checks if element references a specific platform
2264 * @param string $platform Requested platform
2265 * @returns boolean TRUE if platform check succeeds
2269 function supportedPlatform( $platform = NULL ) {
2270 if( !empty( $platform ) ) {
2271 $regex = '/(^|\|)' . $this->db
->databaseType
. '(\||$)/i';
2273 if( preg_match( '/^- /', $platform ) ) {
2274 if (preg_match ( $regex, substr( $platform, 2 ) ) ) {
2275 logMsg( 'Platform ' . $platform . ' is NOT supported' );
2279 if( !preg_match ( $regex, $platform ) ) {
2280 logMsg( 'Platform ' . $platform . ' is NOT supported' );
2286 logMsg( 'Platform ' . $platform . ' is supported' );
2291 * Clears the array of generated SQL.
2295 function clearSQL() {
2296 $this->sqlArray
= array();
2300 * Adds SQL into the SQL array.
2302 * @param mixed $sql SQL to Add
2303 * @return boolean TRUE if successful, else FALSE.
2307 function addSQL( $sql = NULL ) {
2308 if( is_array( $sql ) ) {
2309 foreach( $sql as $line ) {
2310 $this->addSQL( $line );
2316 if( is_string( $sql ) ) {
2317 $this->sqlArray
[] = $sql;
2319 // if executeInline is enabled, and either no errors have occurred or continueOnError is enabled, execute SQL.
2320 if( $this->ExecuteInline() && ( $this->success
== 2 ||
$this->ContinueOnError() ) ) {
2321 $saved = $this->db
->debug
;
2322 $this->db
->debug
= $this->debug
;
2323 $ok = $this->db
->Execute( $sql );
2324 $this->db
->debug
= $saved;
2327 if( $this->debug
) {
2328 ADOConnection
::outp( $this->db
->ErrorMsg() );
2342 * Gets the SQL array in the specified format.
2344 * @param string $format Format
2349 function getSQL( $format = NULL, $sqlArray = NULL ) {
2350 if( !is_array( $sqlArray ) ) {
2351 $sqlArray = $this->sqlArray
;
2354 if( !is_array( $sqlArray ) ) {
2358 switch( strtolower( $format ) ) {
2361 return !empty( $sqlArray ) ?
implode( ";\n\n", $sqlArray ) . ';' : '';
2363 return !empty( $sqlArray ) ?
nl2br( htmlentities( implode( ";\n\n", $sqlArray ) . ';' ) ) : '';
2366 return $this->sqlArray
;
2370 * Destroys an adoSchema object.
2372 * Call this method to clean up after an adoSchema object that is no longer in use.
2373 * @deprecated adoSchema now cleans up automatically.
2375 function Destroy() {
2376 set_magic_quotes_runtime( $this->mgq
);
2382 * Message logging function
2386 function logMsg( $msg, $title = NULL, $force = FALSE ) {
2387 if( XMLS_DEBUG
or $force ) {
2390 if( isset( $title ) ) {
2391 echo '<h3>' . htmlentities( $title ) . '</h3>';
2394 if( @is_object
( $this ) ) {
2395 echo '[' . get_class( $this ) . '] ';