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: jlim $
14 * @author Richard Tango-Lowy & Dan Cech
15 * @version $Revision: 1.62 $
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 __construct( &$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 ) {
170 function create(&$xmls) {
175 * Destroys the object
181 * Checks whether the specified RDBMS is supported by the current
182 * database object or its ranking ancestor.
184 * @param string $platform RDBMS platform name (from ADODB platform list).
185 * @return boolean TRUE if RDBMS is supported; otherwise returns FALSE.
187 function supportedPlatform( $platform = NULL ) {
188 return is_object( $this->parent
) ?
$this->parent
->supportedPlatform( $platform ) : TRUE;
192 * Returns the prefix set by the ranking ancestor of the database object.
194 * @param string $name Prefix string.
195 * @return string Prefix.
197 function prefix( $name = '' ) {
198 return is_object( $this->parent
) ?
$this->parent
->prefix( $name ) : $name;
202 * Extracts a field ID from the specified field.
204 * @param string $field Field.
205 * @return string Field ID.
207 function FieldID( $field ) {
208 return strtoupper( preg_replace( '/^`(.+)`$/', '$1', $field ) );
213 * Creates a table object in ADOdb's datadict format
215 * This class stores information about a database table. As charactaristics
216 * of the table are loaded from the external source, methods and properties
217 * of this class are used to build up the table description in ADOdb's
223 class dbTable
extends dbObject
{
226 * @var string Table name
231 * @var array Field specifier: Meta-information about each field
233 var $fields = array();
236 * @var array List of table indexes.
238 var $indexes = array();
241 * @var array Table options: Table-level options
246 * @var string Field index: Keeps track of which field is currently being processed
251 * @var boolean Mark table for destruction
257 * @var boolean Mark field for destruction (not yet implemented)
260 var $drop_field = array();
263 * @var array Platform-specific options
266 var $currentPlatform = true;
270 * Iniitializes a new table object.
272 * @param string $prefix DB Object prefix
273 * @param array $attributes Array of table attributes.
275 function __construct( &$parent, $attributes = NULL ) {
276 $this->parent
= $parent;
277 $this->name
= $this->prefix($attributes['NAME']);
281 * XML Callback to process start elements. Elements currently
282 * processed are: INDEX, DROP, FIELD, KEY, NOTNULL, AUTOINCREMENT & DEFAULT.
286 function _tag_open( &$parser, $tag, $attributes ) {
287 $this->currentElement
= strtoupper( $tag );
289 switch( $this->currentElement
) {
291 if( !isset( $attributes['PLATFORM'] ) OR $this->supportedPlatform( $attributes['PLATFORM'] ) ) {
292 $index = $this->addIndex( $attributes );
293 xml_set_object( $parser, $index );
297 if( !isset( $attributes['PLATFORM'] ) OR $this->supportedPlatform( $attributes['PLATFORM'] ) ) {
298 $data = $this->addData( $attributes );
299 xml_set_object( $parser, $data );
307 $fieldName = $attributes['NAME'];
308 $fieldType = $attributes['TYPE'];
309 $fieldSize = isset( $attributes['SIZE'] ) ?
$attributes['SIZE'] : NULL;
310 $fieldOpts = !empty( $attributes['OPTS'] ) ?
$attributes['OPTS'] : NULL;
312 $this->addField( $fieldName, $fieldType, $fieldSize, $fieldOpts );
316 case 'AUTOINCREMENT':
320 // Add a field option
321 $this->addFieldOpt( $this->current_field
, $this->currentElement
);
324 // Add a field option to the table object
326 // Work around ADOdb datadict issue that misinterprets empty strings.
327 if( $attributes['VALUE'] == '' ) {
328 $attributes['VALUE'] = " '' ";
331 $this->addFieldOpt( $this->current_field
, $this->currentElement
, $attributes['VALUE'] );
335 // Accept platform-specific options
336 $this->currentPlatform
= ( !isset( $attributes['PLATFORM'] ) OR $this->supportedPlatform( $attributes['PLATFORM'] ) );
339 // print_r( array( $tag, $attributes ) );
344 * XML Callback to process CDATA elements
348 function _tag_cdata( &$parser, $cdata ) {
349 switch( $this->currentElement
) {
350 // Table/field constraint
352 if( isset( $this->current_field
) ) {
353 $this->addFieldOpt( $this->current_field
, $this->currentElement
, $cdata );
355 $this->addTableOpt( $cdata );
358 // Table/field option
360 if( isset( $this->current_field
) ) {
361 $this->addFieldOpt( $this->current_field
, $cdata );
363 $this->addTableOpt( $cdata );
372 * XML Callback to process end elements
376 function _tag_close( &$parser, $tag ) {
377 $this->currentElement
= '';
379 switch( strtoupper( $tag ) ) {
381 $this->parent
->addSQL( $this->create( $this->parent
) );
382 xml_set_object( $parser, $this->parent
);
386 unset($this->current_field
);
390 $this->currentPlatform
= true;
398 * Adds an index to a table object
400 * @param array $attributes Index attributes
401 * @return object dbIndex object
403 function addIndex( $attributes ) {
404 $name = strtoupper( $attributes['NAME'] );
405 $this->indexes
[$name] = new dbIndex( $this, $attributes );
406 return $this->indexes
[$name];
410 * Adds data to a table object
412 * @param array $attributes Data attributes
413 * @return object dbData object
415 function addData( $attributes ) {
416 if( !isset( $this->data
) ) {
417 $this->data
= new dbData( $this, $attributes );
423 * Adds a field to a table object
425 * $name is the name of the table to which the field should be added.
426 * $type is an ADODB datadict field type. The following field types
427 * are supported as of ADODB 3.40:
429 * - X: CLOB (character large object) or largest varchar size
430 * if CLOB is not supported
431 * - C2: Multibyte varchar
432 * - X2: Multibyte CLOB
433 * - B: BLOB (binary large object)
434 * - D: Date (some databases do not support this, and we return a datetime type)
435 * - T: Datetime or Timestamp
436 * - L: Integer field suitable for storing booleans (0 or 1)
437 * - I: Integer (mapped to I4)
438 * - I1: 1-byte integer
439 * - I2: 2-byte integer
440 * - I4: 4-byte integer
441 * - I8: 8-byte integer
442 * - F: Floating point number
443 * - N: Numeric or decimal number
445 * @param string $name Name of the table to which the field will be added.
446 * @param string $type ADODB datadict field type.
447 * @param string $size Field size
448 * @param array $opts Field options array
449 * @return array Field specifier array
451 function addField( $name, $type, $size = NULL, $opts = NULL ) {
452 $field_id = $this->FieldID( $name );
454 // Set the field index so we know where we are
455 $this->current_field
= $field_id;
457 // Set the field name (required)
458 $this->fields
[$field_id]['NAME'] = $name;
460 // Set the field type (required)
461 $this->fields
[$field_id]['TYPE'] = $type;
463 // Set the field size (optional)
464 if( isset( $size ) ) {
465 $this->fields
[$field_id]['SIZE'] = $size;
468 // Set the field options
469 if( isset( $opts ) ) {
470 $this->fields
[$field_id]['OPTS'] = array($opts);
472 $this->fields
[$field_id]['OPTS'] = array();
477 * Adds a field option to the current field specifier
479 * This method adds a field option allowed by the ADOdb datadict
480 * and appends it to the given field.
482 * @param string $field Field name
483 * @param string $opt ADOdb field option
484 * @param mixed $value Field option value
485 * @return array Field specifier array
487 function addFieldOpt( $field, $opt, $value = NULL ) {
488 if( $this->currentPlatform
) {
489 if( !isset( $value ) ) {
490 $this->fields
[$this->FieldID( $field )]['OPTS'][] = $opt;
491 // Add the option and value
493 $this->fields
[$this->FieldID( $field )]['OPTS'][] = array( $opt => $value );
499 * Adds an option to the table
501 * This method takes a comma-separated list of table-level options
502 * and appends them to the table object.
504 * @param string $opt Table option
505 * @return array Options
507 function addTableOpt( $opt ) {
508 if(isset($this->currentPlatform
)) {
509 $this->opts
[$this->parent
->db
->databaseType
] = $opt;
516 * Generates the SQL that will create the table in the database
518 * @param object $xmls adoSchema object
519 * @return array Array containing table creation SQL
521 function create( &$xmls ) {
524 // drop any existing indexes
525 if( is_array( $legacy_indexes = $xmls->dict
->MetaIndexes( $this->name
) ) ) {
526 foreach( $legacy_indexes as $index => $index_details ) {
527 $sql[] = $xmls->dict
->DropIndexSQL( $index, $this->name
);
531 // remove fields to be dropped from table object
532 foreach( $this->drop_field
as $field ) {
533 unset( $this->fields
[$field] );
537 if( is_array( $legacy_fields = $xmls->dict
->MetaColumns( $this->name
) ) ) {
539 if( $this->drop_table
) {
540 $sql[] = $xmls->dict
->DropTableSQL( $this->name
);
545 // drop any existing fields not in schema
546 foreach( $legacy_fields as $field_id => $field ) {
547 if( !isset( $this->fields
[$field_id] ) ) {
548 $sql[] = $xmls->dict
->DropColumnSQL( $this->name
, $field->name
);
551 // if table doesn't exist
553 if( $this->drop_table
) {
557 $legacy_fields = array();
560 // Loop through the field specifier array, building the associative array for the field options
563 foreach( $this->fields
as $field_id => $finfo ) {
564 // Set an empty size if it isn't supplied
565 if( !isset( $finfo['SIZE'] ) ) {
569 // Initialize the field array with the type and size
570 $fldarray[$field_id] = array(
571 'NAME' => $finfo['NAME'],
572 'TYPE' => $finfo['TYPE'],
573 'SIZE' => $finfo['SIZE']
576 // Loop through the options array and add the field options.
577 if( isset( $finfo['OPTS'] ) ) {
578 foreach( $finfo['OPTS'] as $opt ) {
579 // Option has an argument.
580 if( is_array( $opt ) ) {
582 $value = $opt[key( $opt )];
583 @$fldarray[$field_id][$key] .= $value;
584 // Option doesn't have arguments
586 $fldarray[$field_id][$opt] = $opt;
592 if( empty( $legacy_fields ) ) {
593 // Create the new table
594 $sql[] = $xmls->dict
->CreateTableSQL( $this->name
, $fldarray, $this->opts
);
595 logMsg( end( $sql ), 'Generated CreateTableSQL' );
597 // Upgrade an existing table
598 logMsg( "Upgrading {$this->name} using '{$xmls->upgrade}'" );
599 switch( $xmls->upgrade
) {
600 // Use ChangeTableSQL
602 logMsg( 'Generated ChangeTableSQL (ALTERing table)' );
603 $sql[] = $xmls->dict
->ChangeTableSQL( $this->name
, $fldarray, $this->opts
);
606 logMsg( 'Doing upgrade REPLACE (testing)' );
607 $sql[] = $xmls->dict
->DropTableSQL( $this->name
);
608 $sql[] = $xmls->dict
->CreateTableSQL( $this->name
, $fldarray, $this->opts
);
616 foreach( $this->indexes
as $index ) {
617 $sql[] = $index->create( $xmls );
620 if( isset( $this->data
) ) {
621 $sql[] = $this->data
->create( $xmls );
628 * Marks a field or table for destruction
631 if( isset( $this->current_field
) ) {
632 // Drop the current field
633 logMsg( "Dropping field '{$this->current_field}' from table '{$this->name}'" );
634 // $this->drop_field[$this->current_field] = $xmls->dict->DropColumnSQL( $this->name, $this->current_field );
635 $this->drop_field
[$this->current_field
] = $this->current_field
;
637 // Drop the current table
638 logMsg( "Dropping table '{$this->name}'" );
639 // $this->drop_table = $xmls->dict->DropTableSQL( $this->name );
640 $this->drop_table
= TRUE;
646 * Creates an index object in ADOdb's datadict format
648 * This class stores information about a database index. As charactaristics
649 * of the index are loaded from the external source, methods and properties
650 * of this class are used to build up the index description in ADOdb's
656 class dbIndex
extends dbObject
{
659 * @var string Index name
664 * @var array Index options: Index-level options
669 * @var array Indexed fields: Table columns included in this index
671 var $columns = array();
674 * @var boolean Mark index for destruction
680 * Initializes the new dbIndex object.
682 * @param object $parent Parent object
683 * @param array $attributes Attributes
687 function __construct( &$parent, $attributes = NULL ) {
688 $this->parent
= $parent;
690 $this->name
= $this->prefix ($attributes['NAME']);
694 * XML Callback to process start elements
696 * Processes XML opening tags.
697 * Elements currently processed are: DROP, CLUSTERED, BITMAP, UNIQUE, FULLTEXT & HASH.
701 function _tag_open( &$parser, $tag, $attributes ) {
702 $this->currentElement
= strtoupper( $tag );
704 switch( $this->currentElement
) {
714 $this->addIndexOpt( $this->currentElement
);
717 // print_r( array( $tag, $attributes ) );
722 * XML Callback to process CDATA elements
724 * Processes XML cdata.
728 function _tag_cdata( &$parser, $cdata ) {
729 switch( $this->currentElement
) {
732 $this->addField( $cdata );
740 * XML Callback to process end elements
744 function _tag_close( &$parser, $tag ) {
745 $this->currentElement
= '';
747 switch( strtoupper( $tag ) ) {
749 xml_set_object( $parser, $this->parent
);
755 * Adds a field to the index
757 * @param string $name Field name
758 * @return string Field list
760 function addField( $name ) {
761 $this->columns
[$this->FieldID( $name )] = $name;
763 // Return the field list
764 return $this->columns
;
768 * Adds options to the index
770 * @param string $opt Comma-separated list of index options.
771 * @return string Option list
773 function addIndexOpt( $opt ) {
774 $this->opts
[] = $opt;
776 // Return the options list
781 * Generates the SQL that will create the index in the database
783 * @param object $xmls adoSchema object
784 * @return array Array containing index creation SQL
786 function create( &$xmls ) {
791 // eliminate any columns that aren't in the table
792 foreach( $this->columns
as $id => $col ) {
793 if( !isset( $this->parent
->fields
[$id] ) ) {
794 unset( $this->columns
[$id] );
798 return $xmls->dict
->CreateIndexSQL( $this->name
, $this->parent
->name
, $this->columns
, $this->opts
);
802 * Marks an index for destruction
810 * Creates a data object in ADOdb's datadict format
812 * This class stores information about table data, and is called
813 * when we need to load field data into a table.
818 class dbData
extends dbObject
{
825 * Initializes the new dbData object.
827 * @param object $parent Parent object
828 * @param array $attributes Attributes
832 function __construct( &$parent, $attributes = NULL ) {
833 $this->parent
= $parent;
837 * XML Callback to process start elements
839 * Processes XML opening tags.
840 * Elements currently processed are: ROW and F (field).
844 function _tag_open( &$parser, $tag, $attributes ) {
845 $this->currentElement
= strtoupper( $tag );
847 switch( $this->currentElement
) {
849 $this->row
= count( $this->data
);
850 $this->data
[$this->row
] = array();
853 $this->addField($attributes);
855 // print_r( array( $tag, $attributes ) );
860 * XML Callback to process CDATA elements
862 * Processes XML cdata.
866 function _tag_cdata( &$parser, $cdata ) {
867 switch( $this->currentElement
) {
870 $this->addData( $cdata );
878 * XML Callback to process end elements
882 function _tag_close( &$parser, $tag ) {
883 $this->currentElement
= '';
885 switch( strtoupper( $tag ) ) {
887 xml_set_object( $parser, $this->parent
);
893 * Adds a field to the insert
895 * @param string $name Field name
896 * @return string Field list
898 function addField( $attributes ) {
899 // check we're in a valid row
900 if( !isset( $this->row
) ||
!isset( $this->data
[$this->row
] ) ) {
904 // Set the field index so we know where we are
905 if( isset( $attributes['NAME'] ) ) {
906 $this->current_field
= $this->FieldID( $attributes['NAME'] );
908 $this->current_field
= count( $this->data
[$this->row
] );
912 if( !isset( $this->data
[$this->row
][$this->current_field
] ) ) {
913 $this->data
[$this->row
][$this->current_field
] = '';
918 * Adds options to the index
920 * @param string $opt Comma-separated list of index options.
921 * @return string Option list
923 function addData( $cdata ) {
924 // check we're in a valid field
925 if ( isset( $this->data
[$this->row
][$this->current_field
] ) ) {
927 $this->data
[$this->row
][$this->current_field
] .= $cdata;
932 * Generates the SQL that will add/update the data in the database
934 * @param object $xmls adoSchema object
935 * @return array Array containing index creation SQL
937 function create( &$xmls ) {
938 $table = $xmls->dict
->TableName($this->parent
->name
);
939 $table_field_count = count($this->parent
->fields
);
940 $tables = $xmls->db
->MetaTables();
943 $ukeys = $xmls->db
->MetaPrimaryKeys( $table );
944 if( !empty( $this->parent
->indexes
) and !empty( $ukeys ) ) {
945 foreach( $this->parent
->indexes
as $indexObj ) {
946 if( !in_array( $indexObj->name
, $ukeys ) ) $ukeys[] = $indexObj->name
;
950 // eliminate any columns that aren't in the table
951 foreach( $this->data
as $row ) {
952 $table_fields = $this->parent
->fields
;
954 $rawfields = array(); // Need to keep some of the unprocessed data on hand.
956 foreach( $row as $field_id => $field_data ) {
957 if( !array_key_exists( $field_id, $table_fields ) ) {
958 if( is_numeric( $field_id ) ) {
959 $field_id = reset( array_keys( $table_fields ) );
965 $name = $table_fields[$field_id]['NAME'];
967 switch( $table_fields[$field_id]['TYPE'] ) {
973 $fields[$name] = intval($field_data);
980 $fields[$name] = $xmls->db
->qstr( $field_data );
981 $rawfields[$name] = $field_data;
984 unset($table_fields[$field_id]);
988 // check that at least 1 column is specified
989 if( empty( $fields ) ) {
993 // check that no required columns are missing
994 if( count( $fields ) < $table_field_count ) {
995 foreach( $table_fields as $field ) {
996 if( isset( $field['OPTS'] ) and ( in_array( 'NOTNULL', $field['OPTS'] ) ||
in_array( 'KEY', $field['OPTS'] ) ) && !in_array( 'AUTOINCREMENT', $field['OPTS'] ) ) {
1002 // The rest of this method deals with updating existing data records.
1004 if( !in_array( $table, $tables ) or ( $mode = $xmls->existingData() ) == XMLS_MODE_INSERT
) {
1005 // Table doesn't yet exist, so it's safe to insert.
1006 logMsg( "$table doesn't exist, inserting or mode is INSERT" );
1007 $sql[] = 'INSERT INTO '. $table .' ('. implode( ',', array_keys( $fields ) ) .') VALUES ('. implode( ',', $fields ) .')';
1011 // Prepare to test for potential violations. Get primary keys and unique indexes
1012 $mfields = array_merge( $fields, $rawfields );
1013 $keyFields = array_intersect( $ukeys, array_keys( $mfields ) );
1015 if( empty( $ukeys ) or count( $keyFields ) == 0 ) {
1016 // No unique keys in schema, so safe to insert
1017 logMsg( "Either schema or data has no unique keys, so safe to insert" );
1018 $sql[] = 'INSERT INTO '. $table .' ('. implode( ',', array_keys( $fields ) ) .') VALUES ('. implode( ',', $fields ) .')';
1022 // Select record containing matching unique keys.
1024 foreach( $ukeys as $key ) {
1025 if( isset( $mfields[$key] ) and $mfields[$key] ) {
1026 if( $where ) $where .= ' AND ';
1027 $where .= $key . ' = ' . $xmls->db
->qstr( $mfields[$key] );
1030 $records = $xmls->db
->Execute( 'SELECT * FROM ' . $table . ' WHERE ' . $where );
1031 switch( $records->RecordCount() ) {
1033 // No matching record, so safe to insert.
1034 logMsg( "No matching records. Inserting new row with unique data" );
1035 $sql[] = $xmls->db
->GetInsertSQL( $records, $mfields );
1038 // Exactly one matching record, so we can update if the mode permits.
1039 logMsg( "One matching record..." );
1040 if( $mode == XMLS_MODE_UPDATE
) {
1041 logMsg( "...Updating existing row from unique data" );
1042 $sql[] = $xmls->db
->GetUpdateSQL( $records, $mfields );
1046 // More than one matching record; the result is ambiguous, so we must ignore the row.
1047 logMsg( "More than one matching record. Ignoring row." );
1055 * Creates the SQL to execute a list of provided SQL queries
1060 class dbQuerySet
extends dbObject
{
1063 * @var array List of SQL queries
1065 var $queries = array();
1068 * @var string String used to build of a query line by line
1073 * @var string Query prefix key
1075 var $prefixKey = '';
1078 * @var boolean Auto prefix enable (TRUE)
1080 var $prefixMethod = 'AUTO';
1083 * Initializes the query set.
1085 * @param object $parent Parent object
1086 * @param array $attributes Attributes
1088 function __construct( &$parent, $attributes = NULL ) {
1089 $this->parent
= $parent;
1091 // Overrides the manual prefix key
1092 if( isset( $attributes['KEY'] ) ) {
1093 $this->prefixKey
= $attributes['KEY'];
1096 $prefixMethod = isset( $attributes['PREFIXMETHOD'] ) ?
strtoupper( trim( $attributes['PREFIXMETHOD'] ) ) : '';
1098 // Enables or disables automatic prefix prepending
1099 switch( $prefixMethod ) {
1101 $this->prefixMethod
= 'AUTO';
1104 $this->prefixMethod
= 'MANUAL';
1107 $this->prefixMethod
= 'NONE';
1113 * XML Callback to process start elements. Elements currently
1114 * processed are: QUERY.
1118 function _tag_open( &$parser, $tag, $attributes ) {
1119 $this->currentElement
= strtoupper( $tag );
1121 switch( $this->currentElement
) {
1123 // Create a new query in a SQL queryset.
1124 // Ignore this query set if a platform is specified and it's different than the
1125 // current connection platform.
1126 if( !isset( $attributes['PLATFORM'] ) OR $this->supportedPlatform( $attributes['PLATFORM'] ) ) {
1129 $this->discardQuery();
1133 // print_r( array( $tag, $attributes ) );
1138 * XML Callback to process CDATA elements
1140 function _tag_cdata( &$parser, $cdata ) {
1141 switch( $this->currentElement
) {
1142 // Line of queryset SQL data
1144 $this->buildQuery( $cdata );
1152 * XML Callback to process end elements
1156 function _tag_close( &$parser, $tag ) {
1157 $this->currentElement
= '';
1159 switch( strtoupper( $tag ) ) {
1161 // Add the finished query to the open query set.
1165 $this->parent
->addSQL( $this->create( $this->parent
) );
1166 xml_set_object( $parser, $this->parent
);
1175 * Re-initializes the query.
1177 * @return boolean TRUE
1179 function newQuery() {
1186 * Discards the existing query.
1188 * @return boolean TRUE
1190 function discardQuery() {
1191 unset( $this->query
);
1197 * Appends a line to a query that is being built line by line
1199 * @param string $data Line of SQL data or NULL to initialize a new query
1200 * @return string SQL query string.
1202 function buildQuery( $sql = NULL ) {
1203 if( !isset( $this->query
) OR empty( $sql ) ) {
1207 $this->query
.= $sql;
1209 return $this->query
;
1213 * Adds a completed query to the query list
1215 * @return string SQL of added query
1217 function addQuery() {
1218 if( !isset( $this->query
) ) {
1222 $this->queries
[] = $return = trim($this->query
);
1224 unset( $this->query
);
1230 * Creates and returns the current query set
1232 * @param object $xmls adoSchema object
1233 * @return array Query set
1235 function create( &$xmls ) {
1236 foreach( $this->queries
as $id => $query ) {
1237 switch( $this->prefixMethod
) {
1239 // Enable auto prefix replacement
1241 // Process object prefix.
1242 // Evaluate SQL statements to prepend prefix to objects
1243 $query = $this->prefixQuery( '/^\s*((?is)INSERT\s+(INTO\s+)?)((\w+\s*,?\s*)+)(\s.*$)/', $query, $xmls->objectPrefix
);
1244 $query = $this->prefixQuery( '/^\s*((?is)UPDATE\s+(FROM\s+)?)((\w+\s*,?\s*)+)(\s.*$)/', $query, $xmls->objectPrefix
);
1245 $query = $this->prefixQuery( '/^\s*((?is)DELETE\s+(FROM\s+)?)((\w+\s*,?\s*)+)(\s.*$)/', $query, $xmls->objectPrefix
);
1247 // SELECT statements aren't working yet
1248 #$data = preg_replace( '/(?ias)(^\s*SELECT\s+.*\s+FROM)\s+(\W\s*,?\s*)+((?i)\s+WHERE.*$)/', "\1 $prefix\2 \3", $data );
1251 // If prefixKey is set and has a value then we use it to override the default constant XMLS_PREFIX.
1252 // If prefixKey is not set, we use the default constant XMLS_PREFIX
1253 if( isset( $this->prefixKey
) AND( $this->prefixKey
!== '' ) ) {
1254 // Enable prefix override
1255 $query = str_replace( $this->prefixKey
, $xmls->objectPrefix
, $query );
1257 // Use default replacement
1258 $query = str_replace( XMLS_PREFIX
, $xmls->objectPrefix
, $query );
1262 $this->queries
[$id] = trim( $query );
1265 // Return the query set array
1266 return $this->queries
;
1270 * Rebuilds the query with the prefix attached to any objects
1272 * @param string $regex Regex used to add prefix
1273 * @param string $query SQL query string
1274 * @param string $prefix Prefix to be appended to tables, indices, etc.
1275 * @return string Prefixed SQL query string.
1277 function prefixQuery( $regex, $query, $prefix = NULL ) {
1278 if( !isset( $prefix ) ) {
1282 if( preg_match( $regex, $query, $match ) ) {
1283 $preamble = $match[1];
1284 $postamble = $match[5];
1285 $objectList = explode( ',', $match[3] );
1286 // $prefix = $prefix . '_';
1290 foreach( $objectList as $object ) {
1291 if( $prefixedList !== '' ) {
1292 $prefixedList .= ', ';
1295 $prefixedList .= $prefix . trim( $object );
1298 $query = $preamble . ' ' . $prefixedList . ' ' . $postamble;
1306 * Loads and parses an XML file, creating an array of "ready-to-run" SQL statements
1308 * This class is used to load and parse the XML file, to create an array of SQL statements
1309 * that can be used to build a database, and to build the database using the SQL array.
1311 * @tutorial getting_started.pkg
1313 * @author Richard Tango-Lowy & Dan Cech
1314 * @version $Revision: 1.62 $
1321 * @var array Array containing SQL queries to generate all objects
1327 * @var object ADOdb connection object
1333 * @var object ADOdb Data Dictionary
1339 * @var string Current XML element
1342 var $currentElement = '';
1345 * @var string If set (to 'ALTER' or 'REPLACE'), upgrade an existing database
1351 * @var string Optional object prefix
1354 var $objectPrefix = '';
1357 * @var long Original Magic Quotes Runtime value
1363 * @var long System debug
1369 * @var string Regular expression to find schema version
1372 var $versionRegex = '/<schema.*?( version="([^"]*)")?.*?>/';
1375 * @var string Current schema version
1381 * @var int Success of last Schema execution
1386 * @var bool Execute SQL inline as it is generated
1391 * @var bool Continue SQL execution if errors occur
1393 var $continueOnError;
1396 * @var int How to handle existing data rows (insert, update, or ignore)
1401 * Creates an adoSchema object
1403 * Creating an adoSchema object is the first step in processing an XML schema.
1404 * The only parameter is an ADOdb database connection object, which must already
1405 * have been created.
1407 * @param object $db ADOdb database connection object.
1409 function __construct( $db ) {
1410 // Initialize the environment
1411 $this->mgq
= get_magic_quotes_runtime();
1412 #set_magic_quotes_runtime(0);
1413 ini_set("magic_quotes_runtime", 0);
1416 $this->debug
= $this->db
->debug
;
1417 $this->dict
= NewDataDictionary( $this->db
);
1418 $this->sqlArray
= array();
1419 $this->schemaVersion
= XMLS_SCHEMA_VERSION
;
1420 $this->executeInline( XMLS_EXECUTE_INLINE
);
1421 $this->continueOnError( XMLS_CONTINUE_ON_ERROR
);
1422 $this->existingData( XMLS_EXISTING_DATA
);
1423 $this->setUpgradeMethod();
1427 * Sets the method to be used for upgrading an existing database
1429 * Use this method to specify how existing database objects should be upgraded.
1430 * The method option can be set to ALTER, REPLACE, BEST, or NONE. ALTER attempts to
1431 * alter each database object directly, REPLACE attempts to rebuild each object
1432 * from scratch, BEST attempts to determine the best upgrade method for each
1433 * object, and NONE disables upgrading.
1435 * This method is not yet used by AXMLS, but exists for backward compatibility.
1436 * The ALTER method is automatically assumed when the adoSchema object is
1437 * instantiated; other upgrade methods are not currently supported.
1439 * @param string $method Upgrade method (ALTER|REPLACE|BEST|NONE)
1440 * @returns string Upgrade method used
1442 function SetUpgradeMethod( $method = '' ) {
1443 if( !is_string( $method ) ) {
1447 $method = strtoupper( $method );
1449 // Handle the upgrade methods
1452 $this->upgrade
= $method;
1455 $this->upgrade
= $method;
1458 $this->upgrade
= 'ALTER';
1461 $this->upgrade
= 'NONE';
1464 // Use default if no legitimate method is passed.
1465 $this->upgrade
= XMLS_DEFAULT_UPGRADE_METHOD
;
1468 return $this->upgrade
;
1472 * Specifies how to handle existing data row when there is a unique key conflict.
1474 * The existingData setting specifies how the parser should handle existing rows
1475 * when a unique key violation occurs during the insert. This can happen when inserting
1476 * data into an existing table with one or more primary keys or unique indexes.
1477 * The existingData method takes one of three options: XMLS_MODE_INSERT attempts
1478 * to always insert the data as a new row. In the event of a unique key violation,
1479 * the database will generate an error. XMLS_MODE_UPDATE attempts to update the
1480 * any existing rows with the new data based upon primary or unique key fields in
1481 * the schema. If the data row in the schema specifies no unique fields, the row
1482 * data will be inserted as a new row. XMLS_MODE_IGNORE specifies that any data rows
1483 * that would result in a unique key violation be ignored; no inserts or updates will
1484 * take place. For backward compatibility, the default setting is XMLS_MODE_INSERT,
1485 * but XMLS_MODE_UPDATE will generally be the most appropriate setting.
1487 * @param int $mode XMLS_MODE_INSERT, XMLS_MODE_UPDATE, or XMLS_MODE_IGNORE
1488 * @return int current mode
1490 function ExistingData( $mode = NULL ) {
1491 if( is_int( $mode ) ) {
1493 case XMLS_MODE_UPDATE
:
1494 $mode = XMLS_MODE_UPDATE
;
1496 case XMLS_MODE_IGNORE
:
1497 $mode = XMLS_MODE_IGNORE
;
1499 case XMLS_MODE_INSERT
:
1500 $mode = XMLS_MODE_INSERT
;
1503 $mode = XMLS_EXISTING_DATA
;
1506 $this->existingData
= $mode;
1509 return $this->existingData
;
1513 * Enables/disables inline SQL execution.
1515 * Call this method to enable or disable inline execution of the schema. If the mode is set to TRUE (inline execution),
1516 * AXMLS applies the SQL to the database immediately as each schema entity is parsed. If the mode
1517 * is set to FALSE (post execution), AXMLS parses the entire schema and you will need to call adoSchema::ExecuteSchema()
1518 * to apply the schema to the database.
1520 * @param bool $mode execute
1521 * @return bool current execution mode
1523 * @see ParseSchema(), ExecuteSchema()
1525 function ExecuteInline( $mode = NULL ) {
1526 if( is_bool( $mode ) ) {
1527 $this->executeInline
= $mode;
1530 return $this->executeInline
;
1534 * Enables/disables SQL continue on error.
1536 * Call this method to enable or disable continuation of SQL execution if an error occurs.
1537 * If the mode is set to TRUE (continue), AXMLS will continue to apply SQL to the database, even if an error occurs.
1538 * If the mode is set to FALSE (halt), AXMLS will halt execution of generated sql if an error occurs, though parsing
1539 * of the schema will continue.
1541 * @param bool $mode execute
1542 * @return bool current continueOnError mode
1544 * @see addSQL(), ExecuteSchema()
1546 function ContinueOnError( $mode = NULL ) {
1547 if( is_bool( $mode ) ) {
1548 $this->continueOnError
= $mode;
1551 return $this->continueOnError
;
1555 * Loads an XML schema from a file and converts it to SQL.
1557 * Call this method to load the specified schema (see the DTD for the proper format) from
1558 * the filesystem and generate the SQL necessary to create the database
1559 * described. This method automatically converts the schema to the latest
1560 * axmls schema version.
1561 * @see ParseSchemaString()
1563 * @param string $file Name of XML schema file.
1564 * @param bool $returnSchema Return schema rather than parsing.
1565 * @return array Array of SQL queries, ready to execute
1567 function ParseSchema( $filename, $returnSchema = FALSE ) {
1568 return $this->ParseSchemaString( $this->ConvertSchemaFile( $filename ), $returnSchema );
1572 * Loads an XML schema from a file and converts it to SQL.
1574 * Call this method to load the specified schema directly from a file (see
1575 * the DTD for the proper format) and generate the SQL necessary to create
1576 * the database described by the schema. Use this method when you are dealing
1577 * with large schema files. Otherwise, ParseSchema() is faster.
1578 * This method does not automatically convert the schema to the latest axmls
1579 * schema version. You must convert the schema manually using either the
1580 * ConvertSchemaFile() or ConvertSchemaString() method.
1581 * @see ParseSchema()
1582 * @see ConvertSchemaFile()
1583 * @see ConvertSchemaString()
1585 * @param string $file Name of XML schema file.
1586 * @param bool $returnSchema Return schema rather than parsing.
1587 * @return array Array of SQL queries, ready to execute.
1589 * @deprecated Replaced by adoSchema::ParseSchema() and adoSchema::ParseSchemaString()
1590 * @see ParseSchema(), ParseSchemaString()
1592 function ParseSchemaFile( $filename, $returnSchema = FALSE ) {
1594 if( !($fp = fopen( $filename, 'r' )) ) {
1595 logMsg( 'Unable to open file' );
1599 // do version detection here
1600 if( $this->SchemaFileVersion( $filename ) != $this->schemaVersion
) {
1601 logMsg( 'Invalid Schema Version' );
1605 if( $returnSchema ) {
1607 while( $data = fread( $fp, 4096 ) ) {
1608 $xmlstring .= $data . "\n";
1615 $xmlParser = $this->create_parser();
1618 while( $data = fread( $fp, 4096 ) ) {
1619 if( !xml_parse( $xmlParser, $data, feof( $fp ) ) ) {
1621 "XML error: %s at line %d",
1622 xml_error_string( xml_get_error_code( $xmlParser) ),
1623 xml_get_current_line_number( $xmlParser)
1628 xml_parser_free( $xmlParser );
1630 return $this->sqlArray
;
1634 * Converts an XML schema string to SQL.
1636 * Call this method to parse a string containing an XML schema (see the DTD for the proper format)
1637 * and generate the SQL necessary to create the database described by the schema.
1638 * @see ParseSchema()
1640 * @param string $xmlstring XML schema string.
1641 * @param bool $returnSchema Return schema rather than parsing.
1642 * @return array Array of SQL queries, ready to execute.
1644 function ParseSchemaString( $xmlstring, $returnSchema = FALSE ) {
1645 if( !is_string( $xmlstring ) OR empty( $xmlstring ) ) {
1646 logMsg( 'Empty or Invalid Schema' );
1650 // do version detection here
1651 if( $this->SchemaStringVersion( $xmlstring ) != $this->schemaVersion
) {
1652 logMsg( 'Invalid Schema Version' );
1656 if( $returnSchema ) {
1662 $xmlParser = $this->create_parser();
1664 if( !xml_parse( $xmlParser, $xmlstring, TRUE ) ) {
1666 "XML error: %s at line %d",
1667 xml_error_string( xml_get_error_code( $xmlParser) ),
1668 xml_get_current_line_number( $xmlParser)
1672 xml_parser_free( $xmlParser );
1674 return $this->sqlArray
;
1678 * Loads an XML schema from a file and converts it to uninstallation SQL.
1680 * Call this method to load the specified schema (see the DTD for the proper format) from
1681 * the filesystem and generate the SQL necessary to remove the database described.
1682 * @see RemoveSchemaString()
1684 * @param string $file Name of XML schema file.
1685 * @param bool $returnSchema Return schema rather than parsing.
1686 * @return array Array of SQL queries, ready to execute
1688 function RemoveSchema( $filename, $returnSchema = FALSE ) {
1689 return $this->RemoveSchemaString( $this->ConvertSchemaFile( $filename ), $returnSchema );
1693 * Converts an XML schema string to uninstallation SQL.
1695 * Call this method to parse a string containing an XML schema (see the DTD for the proper format)
1696 * and generate the SQL necessary to uninstall the database described by the schema.
1697 * @see RemoveSchema()
1699 * @param string $schema XML schema string.
1700 * @param bool $returnSchema Return schema rather than parsing.
1701 * @return array Array of SQL queries, ready to execute.
1703 function RemoveSchemaString( $schema, $returnSchema = FALSE ) {
1705 // grab current version
1706 if( !( $version = $this->SchemaStringVersion( $schema ) ) ) {
1710 return $this->ParseSchemaString( $this->TransformSchema( $schema, 'remove-' . $version), $returnSchema );
1714 * Applies the current XML schema to the database (post execution).
1716 * Call this method to apply the current schema (generally created by calling
1717 * ParseSchema() or ParseSchemaString() ) to the database (creating the tables, indexes,
1718 * and executing other SQL specified in the schema) after parsing.
1719 * @see ParseSchema(), ParseSchemaString(), ExecuteInline()
1721 * @param array $sqlArray Array of SQL statements that will be applied rather than
1722 * the current schema.
1723 * @param boolean $continueOnErr Continue to apply the schema even if an error occurs.
1724 * @returns integer 0 if failure, 1 if errors, 2 if successful.
1726 function ExecuteSchema( $sqlArray = NULL, $continueOnErr = NULL ) {
1727 if( !is_bool( $continueOnErr ) ) {
1728 $continueOnErr = $this->ContinueOnError();
1731 if( !isset( $sqlArray ) ) {
1732 $sqlArray = $this->sqlArray
;
1735 if( !is_array( $sqlArray ) ) {
1738 $this->success
= $this->dict
->ExecuteSQLArray( $sqlArray, $continueOnErr );
1741 return $this->success
;
1745 * Returns the current SQL array.
1747 * Call this method to fetch the array of SQL queries resulting from
1748 * ParseSchema() or ParseSchemaString().
1750 * @param string $format Format: HTML, TEXT, or NONE (PHP array)
1751 * @return array Array of SQL statements or FALSE if an error occurs
1753 function PrintSQL( $format = 'NONE' ) {
1755 return $this->getSQL( $format, $sqlArray );
1759 * Saves the current SQL array to the local filesystem as a list of SQL queries.
1761 * Call this method to save the array of SQL queries (generally resulting from a
1762 * parsed XML schema) to the filesystem.
1764 * @param string $filename Path and name where the file should be saved.
1765 * @return boolean TRUE if save is successful, else FALSE.
1767 function SaveSQL( $filename = './schema.sql' ) {
1769 if( !isset( $sqlArray ) ) {
1770 $sqlArray = $this->sqlArray
;
1772 if( !isset( $sqlArray ) ) {
1776 $fp = fopen( $filename, "w" );
1778 foreach( $sqlArray as $key => $query ) {
1779 fwrite( $fp, $query . ";\n" );
1785 * Create an xml parser
1787 * @return object PHP XML parser object
1791 function create_parser() {
1792 // Create the parser
1793 $xmlParser = xml_parser_create();
1794 xml_set_object( $xmlParser, $this );
1796 // Initialize the XML callback functions
1797 xml_set_element_handler( $xmlParser, '_tag_open', '_tag_close' );
1798 xml_set_character_data_handler( $xmlParser, '_tag_cdata' );
1804 * XML Callback to process start elements
1808 function _tag_open( &$parser, $tag, $attributes ) {
1809 switch( strtoupper( $tag ) ) {
1811 if( !isset( $attributes['PLATFORM'] ) OR $this->supportedPlatform( $attributes['PLATFORM'] ) ) {
1812 $this->obj
= new dbTable( $this, $attributes );
1813 xml_set_object( $parser, $this->obj
);
1817 if( !isset( $attributes['PLATFORM'] ) OR $this->supportedPlatform( $attributes['PLATFORM'] ) ) {
1818 $this->obj
= new dbQuerySet( $this, $attributes );
1819 xml_set_object( $parser, $this->obj
);
1823 // print_r( array( $tag, $attributes ) );
1829 * XML Callback to process CDATA elements
1833 function _tag_cdata( &$parser, $cdata ) {
1837 * XML Callback to process end elements
1842 function _tag_close( &$parser, $tag ) {
1847 * Converts an XML schema string to the specified DTD version.
1849 * Call this method to convert a string containing an XML schema to a different AXMLS
1850 * DTD version. For instance, to convert a schema created for an pre-1.0 version for
1851 * AXMLS (DTD version 0.1) to a newer version of the DTD (e.g. 0.2). If no DTD version
1852 * parameter is specified, the schema will be converted to the current DTD version.
1853 * If the newFile parameter is provided, the converted schema will be written to the specified
1855 * @see ConvertSchemaFile()
1857 * @param string $schema String containing XML schema that will be converted.
1858 * @param string $newVersion DTD version to convert to.
1859 * @param string $newFile File name of (converted) output file.
1860 * @return string Converted XML schema or FALSE if an error occurs.
1862 function ConvertSchemaString( $schema, $newVersion = NULL, $newFile = NULL ) {
1864 // grab current version
1865 if( !( $version = $this->SchemaStringVersion( $schema ) ) ) {
1869 if( !isset ($newVersion) ) {
1870 $newVersion = $this->schemaVersion
;
1873 if( $version == $newVersion ) {
1876 $result = $this->TransformSchema( $schema, 'convert-' . $version . '-' . $newVersion);
1879 if( is_string( $result ) AND is_string( $newFile ) AND ( $fp = fopen( $newFile, 'w' ) ) ) {
1880 fwrite( $fp, $result );
1888 // compat for pre-4.3 - jlim
1889 function _file_get_contents($path)
1891 if (function_exists('file_get_contents')) return file_get_contents($path);
1892 return join('',file($path));
1896 * Converts an XML schema file to the specified DTD version.
1898 * Call this method to convert the specified XML schema file to a different AXMLS
1899 * DTD version. For instance, to convert a schema created for an pre-1.0 version for
1900 * AXMLS (DTD version 0.1) to a newer version of the DTD (e.g. 0.2). If no DTD version
1901 * parameter is specified, the schema will be converted to the current DTD version.
1902 * If the newFile parameter is provided, the converted schema will be written to the specified
1904 * @see ConvertSchemaString()
1906 * @param string $filename Name of XML schema file that will be converted.
1907 * @param string $newVersion DTD version to convert to.
1908 * @param string $newFile File name of (converted) output file.
1909 * @return string Converted XML schema or FALSE if an error occurs.
1911 function ConvertSchemaFile( $filename, $newVersion = NULL, $newFile = NULL ) {
1913 // grab current version
1914 if( !( $version = $this->SchemaFileVersion( $filename ) ) ) {
1918 if( !isset ($newVersion) ) {
1919 $newVersion = $this->schemaVersion
;
1922 if( $version == $newVersion ) {
1923 $result = _file_get_contents( $filename );
1925 // remove unicode BOM if present
1926 if( substr( $result, 0, 3 ) == sprintf( '%c%c%c', 239, 187, 191 ) ) {
1927 $result = substr( $result, 3 );
1930 $result = $this->TransformSchema( $filename, 'convert-' . $version . '-' . $newVersion, 'file' );
1933 if( is_string( $result ) AND is_string( $newFile ) AND ( $fp = fopen( $newFile, 'w' ) ) ) {
1934 fwrite( $fp, $result );
1941 function TransformSchema( $schema, $xsl, $schematype='string' )
1943 // Fail if XSLT extension is not available
1944 if( ! function_exists( 'xslt_create' ) ) {
1948 $xsl_file = dirname( __FILE__
) . '/xsl/' . $xsl . '.xsl';
1951 if( !is_readable( $xsl_file ) ) {
1955 switch( $schematype )
1958 if( !is_readable( $schema ) ) {
1962 $schema = _file_get_contents( $schema );
1966 if( !is_string( $schema ) ) {
1971 $arguments = array (
1973 '/_xsl' => _file_get_contents( $xsl_file )
1976 // create an XSLT processor
1977 $xh = xslt_create ();
1979 // set error handler
1980 xslt_set_error_handler ($xh, array (&$this, 'xslt_error_handler'));
1982 // process the schema
1983 $result = xslt_process ($xh, 'arg:/_xml', 'arg:/_xsl', NULL, $arguments);
1991 * Processes XSLT transformation errors
1993 * @param object $parser XML parser object
1994 * @param integer $errno Error number
1995 * @param integer $level Error level
1996 * @param array $fields Error information fields
2000 function xslt_error_handler( $parser, $errno, $level, $fields ) {
2001 if( is_array( $fields ) ) {
2003 'Message Type' => ucfirst( $fields['msgtype'] ),
2004 'Message Code' => $fields['code'],
2005 'Message' => $fields['msg'],
2006 'Error Number' => $errno,
2010 switch( $fields['URI'] ) {
2012 $msg['Input'] = 'XML';
2015 $msg['Input'] = 'XSL';
2018 $msg['Input'] = $fields['URI'];
2021 $msg['Line'] = $fields['line'];
2024 'Message Type' => 'Error',
2025 'Error Number' => $errno,
2027 'Fields' => var_export( $fields, TRUE )
2031 $error_details = $msg['Message Type'] . ' in XSLT Transformation' . "\n"
2034 foreach( $msg as $label => $details ) {
2035 $error_details .= '<tr><td><b>' . $label . ': </b></td><td>' . htmlentities( $details ) . '</td></tr>' . "\n";
2038 $error_details .= '</table>';
2040 trigger_error( $error_details, E_USER_ERROR
);
2044 * Returns the AXMLS Schema Version of the requested XML schema file.
2046 * Call this method to obtain the AXMLS DTD version of the requested XML schema file.
2047 * @see SchemaStringVersion()
2049 * @param string $filename AXMLS schema file
2050 * @return string Schema version number or FALSE on error
2052 function SchemaFileVersion( $filename ) {
2054 if( !($fp = fopen( $filename, 'r' )) ) {
2055 // die( 'Unable to open file' );
2060 while( $data = fread( $fp, 4096 ) ) {
2061 if( preg_match( $this->versionRegex
, $data, $matches ) ) {
2062 return !empty( $matches[2] ) ?
$matches[2] : XMLS_DEFAULT_SCHEMA_VERSION
;
2070 * Returns the AXMLS Schema Version of the provided XML schema string.
2072 * Call this method to obtain the AXMLS DTD version of the provided XML schema string.
2073 * @see SchemaFileVersion()
2075 * @param string $xmlstring XML schema string
2076 * @return string Schema version number or FALSE on error
2078 function SchemaStringVersion( $xmlstring ) {
2079 if( !is_string( $xmlstring ) OR empty( $xmlstring ) ) {
2083 if( preg_match( $this->versionRegex
, $xmlstring, $matches ) ) {
2084 return !empty( $matches[2] ) ?
$matches[2] : XMLS_DEFAULT_SCHEMA_VERSION
;
2091 * Extracts an XML schema from an existing database.
2093 * Call this method to create an XML schema string from an existing database.
2094 * If the data parameter is set to TRUE, AXMLS will include the data from the database
2097 * @param boolean $data Include data in schema dump
2098 * @indent string indentation to use
2099 * @prefix string extract only tables with given prefix
2100 * @stripprefix strip prefix string when storing in XML schema
2101 * @return string Generated XML schema
2103 function ExtractSchema( $data = FALSE, $indent = ' ', $prefix = '' , $stripprefix=false) {
2104 $old_mode = $this->db
->SetFetchMode( ADODB_FETCH_NUM
);
2106 $schema = '<?xml version="1.0"?>' . "\n"
2107 . '<schema version="' . $this->schemaVersion
. '">' . "\n";
2108 if( is_array( $tables = $this->db
->MetaTables( 'TABLES' ,false ,($prefix) ?
str_replace('_','\_',$prefix).'%' : '') ) ) {
2109 foreach( $tables as $table ) {
2112 . htmlentities( $stripprefix ?
str_replace($prefix, '', $table) : $table )
2115 // grab details from database
2116 $rs = $this->db
->Execute( 'SELECT * FROM ' . $table . ' WHERE -1' );
2117 $fields = $this->db
->MetaColumns( $table );
2118 $indexes = $this->db
->MetaIndexes( $table );
2120 if( is_array( $fields ) ) {
2121 foreach( $fields as $details ) {
2125 if( isset($details->max_length
) && $details->max_length
> 0 ) {
2126 $extra .= ' size="' . $details->max_length
. '"';
2129 if( isset($details->primary_key
) && $details->primary_key
) {
2130 $content[] = '<KEY/>';
2131 } elseif( isset($details->not_null
) && $details->not_null
) {
2132 $content[] = '<NOTNULL/>';
2135 if( isset($details->has_default
) && $details->has_default
) {
2136 $content[] = '<DEFAULT value="' . htmlentities( $details->default_value
) . '"/>';
2139 if( isset($details->auto_increment
) && $details->auto_increment
) {
2140 $content[] = '<AUTOINCREMENT/>';
2143 if( isset($details->unsigned
) && $details->unsigned
) {
2144 $content[] = '<UNSIGNED/>';
2147 // this stops the creation of 'R' columns,
2148 // AUTOINCREMENT is used to create auto columns
2149 $details->primary_key
= 0;
2150 $type = $rs->MetaType( $details );
2152 $schema .= str_repeat( $indent, 2 ) . '<field name="' . htmlentities( $details->name
) . '" type="' . $type . '"' . $extra;
2154 if( !empty( $content ) ) {
2155 $schema .= ">\n" . str_repeat( $indent, 3 )
2156 . implode( "\n" . str_repeat( $indent, 3 ), $content ) . "\n"
2157 . str_repeat( $indent, 2 ) . '</field>' . "\n";
2164 if( is_array( $indexes ) ) {
2165 foreach( $indexes as $index => $details ) {
2166 $schema .= str_repeat( $indent, 2 ) . '<index name="' . $index . '">' . "\n";
2168 if( $details['unique'] ) {
2169 $schema .= str_repeat( $indent, 3 ) . '<UNIQUE/>' . "\n";
2172 foreach( $details['columns'] as $column ) {
2173 $schema .= str_repeat( $indent, 3 ) . '<col>' . htmlentities( $column ) . '</col>' . "\n";
2176 $schema .= str_repeat( $indent, 2 ) . '</index>' . "\n";
2181 $rs = $this->db
->Execute( 'SELECT * FROM ' . $table );
2183 if( is_object( $rs ) && !$rs->EOF
) {
2184 $schema .= str_repeat( $indent, 2 ) . "<data>\n";
2186 while( $row = $rs->FetchRow() ) {
2187 foreach( $row as $key => $val ) {
2188 if ( $val != htmlentities( $val ) ) {
2189 $row[$key] = '<![CDATA[' . $val . ']]>';
2193 $schema .= str_repeat( $indent, 3 ) . '<row><f>' . implode( '</f><f>', $row ) . "</f></row>\n";
2196 $schema .= str_repeat( $indent, 2 ) . "</data>\n";
2200 $schema .= $indent . "</table>\n";
2204 $this->db
->SetFetchMode( $old_mode );
2206 $schema .= '</schema>';
2211 * Sets a prefix for database objects
2213 * Call this method to set a standard prefix that will be prepended to all database tables
2214 * and indices when the schema is parsed. Calling setPrefix with no arguments clears the prefix.
2216 * @param string $prefix Prefix that will be prepended.
2217 * @param boolean $underscore If TRUE, automatically append an underscore character to the prefix.
2218 * @return boolean TRUE if successful, else FALSE
2220 function SetPrefix( $prefix = '', $underscore = TRUE ) {
2223 case empty( $prefix ):
2224 logMsg( 'Cleared prefix' );
2225 $this->objectPrefix
= '';
2228 case strlen( $prefix ) > XMLS_PREFIX_MAXLEN
:
2229 // prefix contains invalid characters
2230 case !preg_match( '/^[a-z][a-z0-9_]+$/i', $prefix ):
2231 logMsg( 'Invalid prefix: ' . $prefix );
2235 if( $underscore AND substr( $prefix, -1 ) != '_' ) {
2240 logMsg( 'Set prefix: ' . $prefix );
2241 $this->objectPrefix
= $prefix;
2246 * Returns an object name with the current prefix prepended.
2248 * @param string $name Name
2249 * @return string Prefixed name
2253 function prefix( $name = '' ) {
2255 if( !empty( $this->objectPrefix
) ) {
2256 // Prepend the object prefix to the table name
2257 // prepend after quote if used
2258 return preg_replace( '/^(`?)(.+)$/', '$1' . $this->objectPrefix
. '$2', $name );
2261 // No prefix set. Use name provided.
2266 * Checks if element references a specific platform
2268 * @param string $platform Requested platform
2269 * @returns boolean TRUE if platform check succeeds
2273 function supportedPlatform( $platform = NULL ) {
2274 if( !empty( $platform ) ) {
2275 $regex = '/(^|\|)' . $this->db
->databaseType
. '(\||$)/i';
2277 if( preg_match( '/^- /', $platform ) ) {
2278 if (preg_match ( $regex, substr( $platform, 2 ) ) ) {
2279 logMsg( 'Platform ' . $platform . ' is NOT supported' );
2283 if( !preg_match ( $regex, $platform ) ) {
2284 logMsg( 'Platform ' . $platform . ' is NOT supported' );
2290 logMsg( 'Platform ' . $platform . ' is supported' );
2295 * Clears the array of generated SQL.
2299 function clearSQL() {
2300 $this->sqlArray
= array();
2304 * Adds SQL into the SQL array.
2306 * @param mixed $sql SQL to Add
2307 * @return boolean TRUE if successful, else FALSE.
2311 function addSQL( $sql = NULL ) {
2312 if( is_array( $sql ) ) {
2313 foreach( $sql as $line ) {
2314 $this->addSQL( $line );
2320 if( is_string( $sql ) ) {
2321 $this->sqlArray
[] = $sql;
2323 // if executeInline is enabled, and either no errors have occurred or continueOnError is enabled, execute SQL.
2324 if( $this->ExecuteInline() && ( $this->success
== 2 ||
$this->ContinueOnError() ) ) {
2325 $saved = $this->db
->debug
;
2326 $this->db
->debug
= $this->debug
;
2327 $ok = $this->db
->Execute( $sql );
2328 $this->db
->debug
= $saved;
2331 if( $this->debug
) {
2332 ADOConnection
::outp( $this->db
->ErrorMsg() );
2346 * Gets the SQL array in the specified format.
2348 * @param string $format Format
2353 function getSQL( $format = NULL, $sqlArray = NULL ) {
2354 if( !is_array( $sqlArray ) ) {
2355 $sqlArray = $this->sqlArray
;
2358 if( !is_array( $sqlArray ) ) {
2362 switch( strtolower( $format ) ) {
2365 return !empty( $sqlArray ) ?
implode( ";\n\n", $sqlArray ) . ';' : '';
2367 return !empty( $sqlArray ) ?
nl2br( htmlentities( implode( ";\n\n", $sqlArray ) . ';' ) ) : '';
2370 return $this->sqlArray
;
2374 * Destroys an adoSchema object.
2376 * Call this method to clean up after an adoSchema object that is no longer in use.
2377 * @deprecated adoSchema now cleans up automatically.
2379 function Destroy() {
2380 ini_set("magic_quotes_runtime", $this->mgq
);
2381 #set_magic_quotes_runtime( $this->mgq );
2386 * Message logging function
2390 function logMsg( $msg, $title = NULL, $force = FALSE ) {
2391 if( XMLS_DEBUG
or $force ) {
2394 if( isset( $title ) ) {
2395 echo '<h3>' . htmlentities( $title ) . '</h3>';
2398 if( @is_object
( $this ) ) {
2399 echo '[' . get_class( $this ) . '] ';