4 * Read the schema specification and parse into internal data structures
6 class CRM_Core_CodeGen_Specification
{
10 protected $classNames;
15 * @param string $buildVersion which version of the schema to build
17 function parse($schemaPath, $buildVersion) {
18 $this->buildVersion
= $buildVersion;
20 echo "Parsing schema description ".$schemaPath."\n";
21 $dbXML = CRM_Core_CodeGen_Util_Xml
::parse($schemaPath);
24 echo "Extracting database information\n";
25 $this->database
= &$this->getDatabase($dbXML);
26 // print_r( $this->database );
28 $this->classNames
= array();
30 # TODO: peel DAO-specific stuff out of getTables, and spec reading into its own class
31 echo "Extracting table information\n";
32 $this->tables
= $this->getTables($dbXML, $this->database
);
34 $this->resolveForeignKeys($this->tables
, $this->classNames
);
35 $this->tables
= $this->orderTables($this->tables
);
37 // add archive tables here
38 $archiveTables = array( );
39 foreach ($this->tables
as $name => $table ) {
40 if ( $table['archive'] == 'true' ) {
41 $name = 'archive_' . $table['name'];
42 $table['name'] = $name;
43 $table['archive'] = 'false';
44 if ( isset($table['foreignKey']) ) {
45 foreach ($table['foreignKey'] as $fkName => $fkValue) {
46 if ($this->tables
[$fkValue['table']]['archive'] == 'true') {
47 $table['foreignKey'][$fkName]['table'] = 'archive_' . $table['foreignKey'][$fkName]['table'];
48 $table['foreignKey'][$fkName]['uniqName'] =
49 str_replace( 'FK_', 'FK_archive_', $table['foreignKey'][$fkName]['uniqName'] );
52 $archiveTables[$name] = $table;
58 function &getDatabase(&$dbXML) {
59 $database = array('name' => trim((string ) $dbXML->name
));
62 $this->checkAndAppend($attributes, $dbXML, 'character_set', 'DEFAULT CHARACTER SET ', '');
63 $this->checkAndAppend($attributes, $dbXML, 'collate', 'COLLATE ', '');
64 $database['attributes'] = $attributes;
66 $tableAttributes_modern = $tableAttributes_simple = '';
67 $this->checkAndAppend($tableAttributes_modern, $dbXML, 'table_type', 'ENGINE=', '');
68 $this->checkAndAppend($tableAttributes_simple, $dbXML, 'table_type', 'TYPE=', '');
69 $database['tableAttributes_modern'] = trim($tableAttributes_modern . ' ' . $attributes);
70 $database['tableAttributes_simple'] = trim($tableAttributes_simple);
72 $database['comment'] = $this->value('comment', $dbXML, '');
77 function getTables($dbXML, &$database) {
79 foreach ($dbXML->tables
as $tablesXML) {
80 foreach ($tablesXML->table
as $tableXML) {
81 if ($this->value('drop', $tableXML, 0) > 0 and $this->value('drop', $tableXML, 0) <= $this->buildVersion
) {
85 if ($this->value('add', $tableXML, 0) <= $this->buildVersion
) {
86 $this->getTable($tableXML, $database, $tables);
94 function resolveForeignKeys(&$tables, &$classNames) {
95 foreach (array_keys($tables) as $name) {
96 $this->resolveForeignKey($tables, $classNames, $name);
100 function resolveForeignKey(&$tables, &$classNames, $name) {
101 if (!array_key_exists('foreignKey', $tables[$name])) {
105 foreach (array_keys($tables[$name]['foreignKey']) as $fkey) {
106 $ftable = $tables[$name]['foreignKey'][$fkey]['table'];
107 if (!array_key_exists($ftable, $classNames)) {
108 echo "$ftable is not a valid foreign key table in $name\n";
111 $tables[$name]['foreignKey'][$fkey]['className'] = $classNames[$ftable];
112 $tables[$name]['foreignKey'][$fkey]['fileName'] = str_replace('_', '/', $classNames[$ftable]) . '.php';
113 $tables[$name]['fields'][$fkey]['FKClassName'] = $classNames[$ftable];
117 function orderTables(&$tables) {
120 while (!empty($tables)) {
121 foreach (array_keys($tables) as $name) {
122 if ($this->validTable($tables, $ordered, $name)) {
123 $ordered[$name] = $tables[$name];
124 unset($tables[$name]);
131 function validTable(&$tables, &$valid, $name) {
132 if (!array_key_exists('foreignKey', $tables[$name])) {
136 foreach (array_keys($tables[$name]['foreignKey']) as $fkey) {
137 $ftable = $tables[$name]['foreignKey'][$fkey]['table'];
138 if (!array_key_exists($ftable, $valid) && $ftable !== $name) {
145 function getTable($tableXML, &$database, &$tables) {
146 $name = trim((string ) $tableXML->name
);
147 $klass = trim((string ) $tableXML->class);
148 $base = $this->value('base', $tableXML);
149 $sourceFile = "xml/schema/{$base}/{$klass}.xml";
150 $daoPath = "{$base}/DAO/";
151 $pre = str_replace('/', '_', $daoPath);
152 $this->classNames
[$name] = $pre . $klass;
154 $localizable = FALSE;
155 foreach ($tableXML->field
as $fieldXML) {
156 if ($fieldXML->localizable
) {
165 'sourceFile' => $sourceFile,
166 'fileName' => $klass . '.php',
167 'objectName' => $klass,
168 'labelName' => substr($name, 8),
169 'className' => $this->classNames
[$name],
170 'attributes_simple' => trim($database['tableAttributes_simple']),
171 'attributes_modern' => trim($database['tableAttributes_modern']),
172 'comment' => $this->value('comment', $tableXML),
173 'localizable' => $localizable,
174 'log' => $this->value('log', $tableXML, 'false'),
175 'archive' => $this->value('archive', $tableXML, 'false'),
179 foreach ($tableXML->field
as $fieldXML) {
180 if ($this->value('drop', $fieldXML, 0) > 0 and $this->value('drop', $fieldXML, 0) <= $this->buildVersion
) {
184 if ($this->value('add', $fieldXML, 0) <= $this->buildVersion
) {
185 $this->getField($fieldXML, $fields);
189 $table['fields'] = &$fields;
190 $table['hasEnum'] = FALSE;
191 foreach ($table['fields'] as $field) {
192 if ($field['crmType'] == 'CRM_Utils_Type::T_ENUM') {
193 $table['hasEnum'] = TRUE;
198 if ($this->value('primaryKey', $tableXML)) {
199 $this->getPrimaryKey($tableXML->primaryKey
, $fields, $table);
202 // some kind of refresh?
203 CRM_Core_Config
::singleton(FALSE);
204 if ($this->value('index', $tableXML)) {
206 foreach ($tableXML->index
as $indexXML) {
207 if ($this->value('drop', $indexXML, 0) > 0 and $this->value('drop', $indexXML, 0) <= $this->buildVersion
) {
211 $this->getIndex($indexXML, $fields, $index);
213 $table['index'] = &$index;
216 if ($this->value('foreignKey', $tableXML)) {
218 foreach ($tableXML->foreignKey
as $foreignXML) {
219 // print_r($foreignXML);
221 if ($this->value('drop', $foreignXML, 0) > 0 and $this->value('drop', $foreignXML, 0) <= $this->buildVersion
) {
224 if ($this->value('add', $foreignXML, 0) <= $this->buildVersion
) {
225 $this->getForeignKey($foreignXML, $fields, $foreign, $name);
228 $table['foreignKey'] = &$foreign;
231 if ($this->value('dynamicForeignKey', $tableXML)) {
232 $dynamicForeign = array();
233 foreach ($tableXML->dynamicForeignKey
as $foreignXML) {
234 if ($this->value('drop', $foreignXML, 0) > 0 and $this->value('drop', $foreignXML, 0) <= $this->buildVersion
) {
237 if ($this->value('add', $foreignXML, 0) <= $this->buildVersion
) {
238 $this->getDynamicForeignKey($foreignXML, $dynamicForeign, $name);
241 $table['dynamicForeignKey'] = $dynamicForeign;
244 $tables[$name] = &$table;
248 function getField(&$fieldXML, &$fields) {
249 $name = trim((string ) $fieldXML->name
);
250 $field = array('name' => $name, 'localizable' => $fieldXML->localizable
);
251 $type = (string ) $fieldXML->type
;
255 $field['length'] = (int) $fieldXML->length
;
256 $field['sqlType'] = "$type({$field['length']})";
257 $field['phpType'] = 'string';
258 $field['crmType'] = 'CRM_Utils_Type::T_STRING';
259 $field['size'] = $this->getSize($fieldXML);
263 $value = (string ) $fieldXML->values
;
264 $field['sqlType'] = 'enum(';
265 $field['values'] = array();
266 $field['enumValues'] = $value;
267 $values = explode(',', $value);
269 foreach ($values as $v) {
271 $field['values'][] = $v;
274 $field['sqlType'] .= ', ';
277 $field['sqlType'] .= "'$v'";
279 $field['sqlType'] .= ')';
280 $field['phpType'] = $field['sqlType'];
281 $field['crmType'] = 'CRM_Utils_Type::T_ENUM';
285 $field['sqlType'] = $field['phpType'] = $type;
286 $field['crmType'] = 'CRM_Utils_Type::T_' . strtoupper($type);
287 // CRM-13497 see fixme below
288 $field['rows'] = isset($fieldXML->html
) ?
$this->value('rows', $fieldXML->html
) : NULL;
289 $field['cols'] = isset($fieldXML->html
) ?
$this->value('cols', $fieldXML->html
) : NULL;
294 $field['sqlType'] = $field['phpType'] = $type;
295 $field['crmType'] = 'CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME';
299 // need this case since some versions of mysql do not have boolean as a valid column type and hence it
300 // is changed to tinyint. hopefully after 2 yrs this case can be removed.
301 $field['sqlType'] = 'tinyint';
302 $field['phpType'] = $type;
303 $field['crmType'] = 'CRM_Utils_Type::T_' . strtoupper($type);
307 $length = $fieldXML->length ?
$fieldXML->length
: '20,2';
308 $field['sqlType'] = 'decimal(' . $length . ')';
309 $field['phpType'] = 'float';
310 $field['crmType'] = 'CRM_Utils_Type::T_MONEY';
314 $field['sqlType'] = 'double';
315 $field['phpType'] = 'float';
316 $field['crmType'] = 'CRM_Utils_Type::T_FLOAT';
320 $field['sqlType'] = $field['phpType'] = $type;
321 if ($type == 'int unsigned') {
322 $field['crmType'] = 'CRM_Utils_Type::T_INT';
325 $field['crmType'] = 'CRM_Utils_Type::T_' . strtoupper($type);
330 $field['required'] = $this->value('required', $fieldXML);
331 $field['collate'] = $this->value('collate', $fieldXML);
332 $field['comment'] = $this->value('comment', $fieldXML);
333 $field['default'] = $this->value('default', $fieldXML);
334 $field['import'] = $this->value('import', $fieldXML);
335 if ($this->value('export', $fieldXML)) {
336 $field['export'] = $this->value('export', $fieldXML);
339 $field['export'] = $this->value('import', $fieldXML);
341 $field['rule'] = $this->value('rule', $fieldXML);
342 $field['title'] = $this->value('title', $fieldXML);
343 if (!$field['title']) {
344 $field['title'] = $this->composeTitle($name);
346 $field['headerPattern'] = $this->value('headerPattern', $fieldXML);
347 $field['dataPattern'] = $this->value('dataPattern', $fieldXML);
348 $field['uniqueName'] = $this->value('uniqueName', $fieldXML);
349 $field['html'] = $this->value('html', $fieldXML);
350 if (!empty($field['html'])) {
351 $validOptions = array(
353 /* Fixme: prior to CRM-13497 these were in a flat structure
354 // CRM-13497 moved them to be nested within 'html' but there's no point
355 // making that change in the DAOs right now since we are in the process of
356 // moving to docrtine anyway.
357 // So translating from nested xml back to flat structure for now.
362 $field['html'] = array();
363 foreach ($validOptions as $htmlOption) {
364 if(!empty($fieldXML->html
->$htmlOption)){
365 $field['html'][$htmlOption] = $this->value($htmlOption, $fieldXML->html
);
369 $field['pseudoconstant'] = $this->value('pseudoconstant', $fieldXML);
370 if(!empty($field['pseudoconstant'])){
371 //ok this is a bit long-winded but it gets there & is consistent with above approach
372 $field['pseudoconstant'] = array();
373 $validOptions = array(
374 // Fields can specify EITHER optionGroupName OR table, not both
375 // (since declaring optionGroupName means we are using the civicrm_option_value table)
378 // If table is specified, keyColumn and labelColumn are also required
381 // Non-translated machine name for programmatic lookup. Defaults to 'name' if that column exists
383 // Where clause snippet (will be joined to the rest of the query with AND operator)
386 foreach ($validOptions as $pseudoOption) {
387 if(!empty($fieldXML->pseudoconstant
->$pseudoOption)){
388 $field['pseudoconstant'][$pseudoOption] = $this->value($pseudoOption, $fieldXML->pseudoconstant
);
391 // For now, fields that have option lists that are not in the db can simply
392 // declare an empty pseudoconstant tag and we'll add this placeholder.
393 // That field's BAO::buildOptions fn will need to be responsible for generating the option list
394 if (empty($field['pseudoconstant'])) {
395 $field['pseudoconstant'] = 'not in database';
398 $fields[$name] = &$field;
401 function composeTitle($name) {
402 $names = explode('_', strtolower($name));
404 for ($i = 0; $i < count($names); $i++
) {
405 if ($names[$i] === 'id' ||
$names[$i] === 'is') {
406 // id's do not get titles
410 if ($names[$i] === 'im') {
414 $names[$i] = ucfirst(trim($names[$i]));
417 $title = $title . ' ' . $names[$i];
422 function getPrimaryKey(&$primaryXML, &$fields, &$table) {
423 $name = trim((string ) $primaryXML->name
);
425 /** need to make sure there is a field of type name */
426 if (!array_key_exists($name, $fields)) {
427 echo "primary key $name in $table->name does not have a field definition, ignoring\n";
431 // set the autoincrement property of the field
432 $auto = $this->value('autoincrement', $primaryXML);
433 $fields[$name]['autoincrement'] = $auto;
436 'autoincrement' => $auto,
438 $table['primaryKey'] = &$primaryKey;
441 function getIndex(&$indexXML, &$fields, &$indices) {
442 //echo "\n\n*******************************************************\n";
443 //echo "entering getIndex\n";
446 // empty index name is fine
447 $indexName = trim((string)$indexXML->name
);
448 $index['name'] = $indexName;
449 $index['field'] = array();
452 foreach ($indexXML->fieldName
as $v) {
453 $fieldName = (string)($v);
454 $length = (string)($v['length']);
455 if (strlen($length) > 0) {
456 $fieldName = "$fieldName($length)";
458 $index['field'][] = $fieldName;
461 $index['localizable'] = FALSE;
462 foreach ($index['field'] as $fieldName) {
463 if (isset($fields[$fieldName]) and $fields[$fieldName]['localizable']) {
464 $index['localizable'] = TRUE;
469 // check for unique index
470 if ($this->value('unique', $indexXML)) {
471 $index['unique'] = TRUE;
474 //echo "\$index = \n";
477 // field array cannot be empty
478 if (empty($index['field'])) {
479 echo "No fields defined for index $indexName\n";
483 // all fieldnames have to be defined and should exist in schema.
484 foreach ($index['field'] as $fieldName) {
486 echo "Invalid field defination for index $indexName\n";
489 $parenOffset = strpos($fieldName, '(');
490 if ($parenOffset > 0) {
491 $fieldName = substr($fieldName, 0, $parenOffset);
493 if (!array_key_exists($fieldName, $fields)) {
494 echo "Table does not contain $fieldName\n";
499 $indices[$indexName] = &$index;
502 function getForeignKey(&$foreignXML, &$fields, &$foreignKeys, &$currentTableName) {
503 $name = trim((string ) $foreignXML->name
);
505 /** need to make sure there is a field of type name */
506 if (!array_key_exists($name, $fields)) {
507 echo "foreign $name in $currentTableName does not have a field definition, ignoring\n";
511 /** need to check for existence of table and key **/
512 $table = trim($this->value('table', $foreignXML));
516 'uniqName' => "FK_{$currentTableName}_{$name}",
517 'key' => trim($this->value('key', $foreignXML)),
518 'import' => $this->value('import', $foreignXML, FALSE),
519 'export' => $this->value('import', $foreignXML, FALSE),
520 // we do this matching in a seperate phase (resolveForeignKeys)
522 'onDelete' => $this->value('onDelete', $foreignXML, FALSE),
524 $foreignKeys[$name] = &$foreignKey;
527 function getDynamicForeignKey(&$foreignXML, &$dynamicForeignKeys) {
529 'idColumn' => trim($foreignXML->idColumn
),
530 'typeColumn' => trim($foreignXML->typeColumn
),
531 'key' => trim($this->value('key', $foreignXML)),
533 $dynamicForeignKeys[] = $foreignKey;
536 protected function value($key, &$object, $default = NULL) {
537 if (isset($object->$key)) {
538 return (string ) $object->$key;
543 protected function checkAndAppend(&$attributes, &$object, $name, $pre = NULL, $post = NULL) {
544 if (!isset($object->$name)) {
548 $value = $pre . trim($object->$name) . $post;
549 $this->append($attributes, ' ', trim($value));
552 protected function append(&$str, $delim, $name) {
557 if (is_array($name)) {
558 foreach ($name as $n) {
575 $str .= $delim . $name;
581 * Sets the size property of a textfield
582 * See constants defined in CRM_Utils_Type for possible values
584 protected function getSize($fieldXML) {
585 // Extract from <size> tag if supplied
586 if (!empty($fieldXML->html
) && $this->value('size', $fieldXML->html
)) {
587 $const = 'CRM_Utils_Type::' . strtoupper($fieldXML->html
->size
);
588 if (defined($const)) {
592 // Infer from <length> tag if <size> was not explicitly set or was invalid
594 // This map is slightly different from CRM_Core_Form_Renderer::$_sizeMapper
595 // Because we usually want fields to render as smaller than their maxlength
605 foreach ($sizes as $length => $name) {
606 if ($fieldXML->length
<= $length) {
607 return "CRM_Utils_Type::$name";
610 return 'CRM_Utils_Type::HUGE';