4 * Read the schema specification and parse into internal data structures
6 class CRM_Core_CodeGen_Specification
{
10 protected $classNames;
16 * @param string $buildVersion
17 * Which version of the schema to build.
19 public function parse($schemaPath, $buildVersion) {
20 $this->buildVersion
= $buildVersion;
22 echo "Parsing schema description " . $schemaPath . "\n";
23 $dbXML = CRM_Core_CodeGen_Util_Xml
::parse($schemaPath);
26 echo "Extracting database information\n";
27 $this->database
= &$this->getDatabase($dbXML);
28 // print_r( $this->database );
30 $this->classNames
= array();
32 # TODO: peel DAO-specific stuff out of getTables, and spec reading into its own class
33 echo "Extracting table information\n";
34 $this->tables
= $this->getTables($dbXML, $this->database
);
36 $this->resolveForeignKeys($this->tables
, $this->classNames
);
37 $this->tables
= $this->orderTables($this->tables
);
39 // add archive tables here
40 $archiveTables = array();
41 foreach ($this->tables
as $name => $table) {
42 if ($table['archive'] == 'true') {
43 $name = 'archive_' . $table['name'];
44 $table['name'] = $name;
45 $table['archive'] = 'false';
46 if (isset($table['foreignKey'])) {
47 foreach ($table['foreignKey'] as $fkName => $fkValue) {
48 if ($this->tables
[$fkValue['table']]['archive'] == 'true') {
49 $table['foreignKey'][$fkName]['table'] = 'archive_' . $table['foreignKey'][$fkName]['table'];
50 $table['foreignKey'][$fkName]['uniqName'] =
51 str_replace('FK_', 'FK_archive_', $table['foreignKey'][$fkName]['uniqName']);
54 $archiveTables[$name] = $table;
65 public function &getDatabase(&$dbXML) {
66 $database = array('name' => trim((string ) $dbXML->name
));
69 $this->checkAndAppend($attributes, $dbXML, 'character_set', 'DEFAULT CHARACTER SET ', '');
70 $this->checkAndAppend($attributes, $dbXML, 'collate', 'COLLATE ', '');
71 $database['attributes'] = $attributes;
73 $tableAttributes_modern = $tableAttributes_simple = '';
74 $this->checkAndAppend($tableAttributes_modern, $dbXML, 'table_type', 'ENGINE=', '');
75 $this->checkAndAppend($tableAttributes_simple, $dbXML, 'table_type', 'TYPE=', '');
76 $database['tableAttributes_modern'] = trim($tableAttributes_modern . ' ' . $attributes);
77 $database['tableAttributes_simple'] = trim($tableAttributes_simple);
79 $database['comment'] = $this->value('comment', $dbXML, '');
90 public function getTables($dbXML, &$database) {
92 foreach ($dbXML->tables
as $tablesXML) {
93 foreach ($tablesXML->table
as $tableXML) {
94 if ($this->value('drop', $tableXML, 0) > 0 and $this->value('drop', $tableXML, 0) <= $this->buildVersion
) {
98 if ($this->value('add', $tableXML, 0) <= $this->buildVersion
) {
99 $this->getTable($tableXML, $database, $tables);
109 * @param string $classNames
111 public function resolveForeignKeys(&$tables, &$classNames) {
112 foreach (array_keys($tables) as $name) {
113 $this->resolveForeignKey($tables, $classNames, $name);
119 * @param string $classNames
120 * @param string $name
122 public function resolveForeignKey(&$tables, &$classNames, $name) {
123 if (!array_key_exists('foreignKey', $tables[$name])) {
127 foreach (array_keys($tables[$name]['foreignKey']) as $fkey) {
128 $ftable = $tables[$name]['foreignKey'][$fkey]['table'];
129 if (!array_key_exists($ftable, $classNames)) {
130 echo "$ftable is not a valid foreign key table in $name\n";
133 $tables[$name]['foreignKey'][$fkey]['className'] = $classNames[$ftable];
134 $tables[$name]['foreignKey'][$fkey]['fileName'] = str_replace('_', '/', $classNames[$ftable]) . '.php';
135 $tables[$name]['fields'][$fkey]['FKClassName'] = $classNames[$ftable];
144 public function orderTables(&$tables) {
147 while (!empty($tables)) {
148 foreach (array_keys($tables) as $name) {
149 if ($this->validTable($tables, $ordered, $name)) {
150 $ordered[$name] = $tables[$name];
151 unset($tables[$name]);
161 * @param string $name
165 public function validTable(&$tables, &$valid, $name) {
166 if (!array_key_exists('foreignKey', $tables[$name])) {
170 foreach (array_keys($tables[$name]['foreignKey']) as $fkey) {
171 $ftable = $tables[$name]['foreignKey'][$fkey]['table'];
172 if (!array_key_exists($ftable, $valid) && $ftable !== $name) {
184 public function getTable($tableXML, &$database, &$tables) {
185 $name = trim((string ) $tableXML->name
);
186 $klass = trim((string ) $tableXML->class);
187 $base = $this->value('base', $tableXML);
188 $sourceFile = "xml/schema/{$base}/{$klass}.xml";
189 $daoPath = "{$base}/DAO/";
190 $pre = str_replace('/', '_', $daoPath);
191 $this->classNames
[$name] = $pre . $klass;
193 $localizable = FALSE;
194 foreach ($tableXML->field
as $fieldXML) {
195 if ($fieldXML->localizable
) {
204 'sourceFile' => $sourceFile,
205 'fileName' => $klass . '.php',
206 'objectName' => $klass,
207 'labelName' => substr($name, 8),
208 'className' => $this->classNames
[$name],
209 'attributes_simple' => trim($database['tableAttributes_simple']),
210 'attributes_modern' => trim($database['tableAttributes_modern']),
211 'comment' => $this->value('comment', $tableXML),
212 'localizable' => $localizable,
213 'log' => $this->value('log', $tableXML, 'false'),
214 'archive' => $this->value('archive', $tableXML, 'false'),
218 foreach ($tableXML->field
as $fieldXML) {
219 if ($this->value('drop', $fieldXML, 0) > 0 and $this->value('drop', $fieldXML, 0) <= $this->buildVersion
) {
223 if ($this->value('add', $fieldXML, 0) <= $this->buildVersion
) {
224 $this->getField($fieldXML, $fields);
228 $table['fields'] = &$fields;
230 if ($this->value('primaryKey', $tableXML)) {
231 $this->getPrimaryKey($tableXML->primaryKey
, $fields, $table);
234 // some kind of refresh?
235 CRM_Core_Config
::singleton(FALSE);
236 if ($this->value('index', $tableXML)) {
238 foreach ($tableXML->index
as $indexXML) {
239 if ($this->value('drop', $indexXML, 0) > 0 and $this->value('drop', $indexXML, 0) <= $this->buildVersion
) {
243 $this->getIndex($indexXML, $fields, $index);
245 $table['index'] = &$index;
248 if ($this->value('foreignKey', $tableXML)) {
250 foreach ($tableXML->foreignKey
as $foreignXML) {
251 // print_r($foreignXML);
253 if ($this->value('drop', $foreignXML, 0) > 0 and $this->value('drop', $foreignXML, 0) <= $this->buildVersion
) {
256 if ($this->value('add', $foreignXML, 0) <= $this->buildVersion
) {
257 $this->getForeignKey($foreignXML, $fields, $foreign, $name);
260 $table['foreignKey'] = &$foreign;
263 if ($this->value('dynamicForeignKey', $tableXML)) {
264 $dynamicForeign = array();
265 foreach ($tableXML->dynamicForeignKey
as $foreignXML) {
266 if ($this->value('drop', $foreignXML, 0) > 0 and $this->value('drop', $foreignXML, 0) <= $this->buildVersion
) {
269 if ($this->value('add', $foreignXML, 0) <= $this->buildVersion
) {
270 $this->getDynamicForeignKey($foreignXML, $dynamicForeign, $name);
273 $table['dynamicForeignKey'] = $dynamicForeign;
276 $tables[$name] = &$table;
284 public function getField(&$fieldXML, &$fields) {
285 $name = trim((string ) $fieldXML->name
);
286 $field = array('name' => $name, 'localizable' => $fieldXML->localizable
);
287 $type = (string ) $fieldXML->type
;
291 $field['length'] = (int) $fieldXML->length
;
292 $field['sqlType'] = "$type({$field['length']})";
293 $field['phpType'] = 'string';
294 $field['crmType'] = 'CRM_Utils_Type::T_STRING';
295 $field['size'] = $this->getSize($fieldXML);
299 $field['sqlType'] = $field['phpType'] = $type;
300 $field['crmType'] = 'CRM_Utils_Type::T_' . strtoupper($type);
301 // CRM-13497 see fixme below
302 $field['rows'] = isset($fieldXML->html
) ?
$this->value('rows', $fieldXML->html
) : NULL;
303 $field['cols'] = isset($fieldXML->html
) ?
$this->value('cols', $fieldXML->html
) : NULL;
309 $field['sqlType'] = $field['phpType'] = $type;
310 $field['crmType'] = 'CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME';
314 // need this case since some versions of mysql do not have boolean as a valid column type and hence it
315 // is changed to tinyint. hopefully after 2 yrs this case can be removed.
316 $field['sqlType'] = 'tinyint';
317 $field['phpType'] = $type;
318 $field['crmType'] = 'CRM_Utils_Type::T_' . strtoupper($type);
322 $length = $fieldXML->length ?
$fieldXML->length
: '20,2';
323 $field['sqlType'] = 'decimal(' . $length . ')';
324 $field['phpType'] = 'float';
325 $field['crmType'] = 'CRM_Utils_Type::T_MONEY';
326 $field['precision'] = $length;
330 $field['sqlType'] = 'double';
331 $field['phpType'] = 'float';
332 $field['crmType'] = 'CRM_Utils_Type::T_FLOAT';
336 $field['sqlType'] = $field['phpType'] = $type;
337 if ($type == 'int unsigned') {
338 $field['crmType'] = 'CRM_Utils_Type::T_INT';
341 $field['crmType'] = 'CRM_Utils_Type::T_' . strtoupper($type);
346 $field['required'] = $this->value('required', $fieldXML);
347 $field['collate'] = $this->value('collate', $fieldXML);
348 $field['comment'] = $this->value('comment', $fieldXML);
349 $field['default'] = $this->value('default', $fieldXML);
350 $field['import'] = $this->value('import', $fieldXML);
351 if ($this->value('export', $fieldXML)) {
352 $field['export'] = $this->value('export', $fieldXML);
355 $field['export'] = $this->value('import', $fieldXML);
357 $field['rule'] = $this->value('rule', $fieldXML);
358 $field['title'] = $this->value('title', $fieldXML);
359 if (!$field['title']) {
360 $field['title'] = $this->composeTitle($name);
362 $field['headerPattern'] = $this->value('headerPattern', $fieldXML);
363 $field['dataPattern'] = $this->value('dataPattern', $fieldXML);
364 $field['uniqueName'] = $this->value('uniqueName', $fieldXML);
365 $field['html'] = $this->value('html', $fieldXML);
366 if (!empty($field['html'])) {
367 $validOptions = array(
369 /* Fixme: prior to CRM-13497 these were in a flat structure
370 // CRM-13497 moved them to be nested within 'html' but there's no point
371 // making that change in the DAOs right now since we are in the process of
372 // moving to docrtine anyway.
373 // So translating from nested xml back to flat structure for now.
378 $field['html'] = array();
379 foreach ($validOptions as $htmlOption) {
380 if (!empty($fieldXML->html
->$htmlOption)) {
381 $field['html'][$htmlOption] = $this->value($htmlOption, $fieldXML->html
);
385 $field['pseudoconstant'] = $this->value('pseudoconstant', $fieldXML);
386 if (!empty($field['pseudoconstant'])) {
387 //ok this is a bit long-winded but it gets there & is consistent with above approach
388 $field['pseudoconstant'] = array();
389 $validOptions = array(
390 // Fields can specify EITHER optionGroupName OR table, not both
391 // (since declaring optionGroupName means we are using the civicrm_option_value table)
394 // If table is specified, keyColumn and labelColumn are also required
397 // Non-translated machine name for programmatic lookup. Defaults to 'name' if that column exists
399 // Where clause snippet (will be joined to the rest of the query with AND operator)
401 // callback funtion incase of static arrays
404 foreach ($validOptions as $pseudoOption) {
405 if (!empty($fieldXML->pseudoconstant
->$pseudoOption)) {
406 $field['pseudoconstant'][$pseudoOption] = $this->value($pseudoOption, $fieldXML->pseudoconstant
);
409 // For now, fields that have option lists that are not in the db can simply
410 // declare an empty pseudoconstant tag and we'll add this placeholder.
411 // That field's BAO::buildOptions fn will need to be responsible for generating the option list
412 if (empty($field['pseudoconstant'])) {
413 $field['pseudoconstant'] = 'not in database';
416 $fields[$name] = &$field;
420 * @param string $name
424 public function composeTitle($name) {
425 $names = explode('_', strtolower($name));
427 for ($i = 0; $i < count($names); $i++
) {
428 if ($names[$i] === 'id' ||
$names[$i] === 'is') {
429 // id's do not get titles
433 if ($names[$i] === 'im') {
437 $names[$i] = ucfirst(trim($names[$i]));
440 $title = $title . ' ' . $names[$i];
450 public function getPrimaryKey(&$primaryXML, &$fields, &$table) {
451 $name = trim((string ) $primaryXML->name
);
453 /** need to make sure there is a field of type name */
454 if (!array_key_exists($name, $fields)) {
455 echo "primary key $name in $table->name does not have a field definition, ignoring\n";
459 // set the autoincrement property of the field
460 $auto = $this->value('autoincrement', $primaryXML);
461 $fields[$name]['autoincrement'] = $auto;
464 'autoincrement' => $auto,
466 $table['primaryKey'] = &$primaryKey;
474 public function getIndex(&$indexXML, &$fields, &$indices) {
475 //echo "\n\n*******************************************************\n";
476 //echo "entering getIndex\n";
479 // empty index name is fine
480 $indexName = trim((string) $indexXML->name
);
481 $index['name'] = $indexName;
482 $index['field'] = array();
485 foreach ($indexXML->fieldName
as $v) {
486 $fieldName = (string) ($v);
487 $length = (string) ($v['length']);
488 if (strlen($length) > 0) {
489 $fieldName = "$fieldName($length)";
491 $index['field'][] = $fieldName;
494 $index['localizable'] = FALSE;
495 foreach ($index['field'] as $fieldName) {
496 if (isset($fields[$fieldName]) and $fields[$fieldName]['localizable']) {
497 $index['localizable'] = TRUE;
502 // check for unique index
503 if ($this->value('unique', $indexXML)) {
504 $index['unique'] = TRUE;
507 //echo "\$index = \n";
510 // field array cannot be empty
511 if (empty($index['field'])) {
512 echo "No fields defined for index $indexName\n";
516 // all fieldnames have to be defined and should exist in schema.
517 foreach ($index['field'] as $fieldName) {
519 echo "Invalid field defination for index $indexName\n";
522 $parenOffset = strpos($fieldName, '(');
523 if ($parenOffset > 0) {
524 $fieldName = substr($fieldName, 0, $parenOffset);
526 if (!array_key_exists($fieldName, $fields)) {
527 echo "Table does not contain $fieldName\n";
532 $indices[$indexName] = &$index;
538 * @param $foreignKeys
539 * @param string $currentTableName
541 public function getForeignKey(&$foreignXML, &$fields, &$foreignKeys, &$currentTableName) {
542 $name = trim((string ) $foreignXML->name
);
544 /** need to make sure there is a field of type name */
545 if (!array_key_exists($name, $fields)) {
546 echo "foreign $name in $currentTableName does not have a field definition, ignoring\n";
550 /** need to check for existence of table and key **/
551 $table = trim($this->value('table', $foreignXML));
555 'uniqName' => "FK_{$currentTableName}_{$name}",
556 'key' => trim($this->value('key', $foreignXML)),
557 'import' => $this->value('import', $foreignXML, FALSE),
558 'export' => $this->value('import', $foreignXML, FALSE),
559 // we do this matching in a seperate phase (resolveForeignKeys)
561 'onDelete' => $this->value('onDelete', $foreignXML, FALSE),
563 $foreignKeys[$name] = &$foreignKey;
568 * @param $dynamicForeignKeys
570 public function getDynamicForeignKey(&$foreignXML, &$dynamicForeignKeys) {
572 'idColumn' => trim($foreignXML->idColumn
),
573 'typeColumn' => trim($foreignXML->typeColumn
),
574 'key' => trim($this->value('key', $foreignXML)),
576 $dynamicForeignKeys[] = $foreignKey;
582 * @param null $default
584 * @return null|string
586 protected function value($key, &$object, $default = NULL) {
587 if (isset($object->$key)) {
588 return (string ) $object->$key;
596 * @param string $name
600 protected function checkAndAppend(&$attributes, &$object, $name, $pre = NULL, $post = NULL) {
601 if (!isset($object->$name)) {
605 $value = $pre . trim($object->$name) . $post;
606 $this->append($attributes, ' ', trim($value));
614 protected function append(&$str, $delim, $name) {
619 if (is_array($name)) {
620 foreach ($name as $n) {
637 $str .= $delim . $name;
643 * Sets the size property of a textfield
644 * See constants defined in CRM_Utils_Type for possible values
646 protected function getSize($fieldXML) {
647 // Extract from <size> tag if supplied
648 if (!empty($fieldXML->html
) && $this->value('size', $fieldXML->html
)) {
649 $const = 'CRM_Utils_Type::' . strtoupper($fieldXML->html
->size
);
650 if (defined($const)) {
654 // Infer from <length> tag if <size> was not explicitly set or was invalid
656 // This map is slightly different from CRM_Core_Form_Renderer::$_sizeMapper
657 // Because we usually want fields to render as smaller than their maxlength
667 foreach ($sizes as $length => $name) {
668 if ($fieldXML->length
<= $length) {
669 return "CRM_Utils_Type::$name";
672 return 'CRM_Utils_Type::HUGE';