5 * This applies database files from
6 * a) OLD - {MODULE}/DataObjects/XXXX.{dbtype}.sql
8 * b) NEW - {MODULE}/sql/XXX.sql (SHARED or translable)
9 * and {MODULE}/{dbtype}/XXX.sql (SHARED or translable)
14 require_once 'Pman.php';
15 class Pman_Core_UpdateDatabase extends Pman
18 static $cli_desc = "Update SQL - Beta (it will run updateData of all modules)";
20 static $cli_opts = array(
23 'desc' => 'prefix for the password (eg. fred > xxx4fred - prefix is xxx4)',
30 'desc' => 'only run the updateData - do not run import the tables and procedures.',
37 'add-company' => array(
38 'desc' => 'add a company name of the company',
44 'add-company-with-type' => array(
45 'desc' => 'the type of company (default OWNER)',
52 'desc' => 'Initialize the database (pg only supported)',
58 'only-module-sql' => array(
59 'desc' => 'Only run sql import on this modules - eg. Core',
64 'procedures-only' => array(
65 'desc' => 'Only import procedures (not supported by most modules yet) - ignores sql directory',
72 'json-person' => array(
73 'desc' => 'Person JSON file',
81 static function cli_opts()
84 $ret = self::$cli_opts;
85 $ff = HTML_FlexyFramework::get();
87 $mods = $a->modulesList();
88 foreach($mods as $m) {
90 $fd = $ff->rootDir. "/Pman/$m/UpdateDatabase.php";
91 if (!file_exists($fd)) {
97 $cls = new ReflectionClass('Pman_'. $m . '_UpdateDatabase');
99 $ret = array_merge($ret, $cls->getStaticPropertyValue('cli_opts'));
108 var $disabled = array();
115 $ff = HTML_FlexyFramework::get();
116 if (!empty($ff->cli)) {
121 parent::getAuth(); // load company!
122 $au = $this->getAuthUser();
123 if (!$au || $au->company()->comptype != 'OWNER') {
124 $this->jerr("Not authenticated", array('authFailure' => true));
126 $this->authUser = $au;
130 function get($args, $opts)
132 PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, array($this, 'onPearError'));
134 $ff = HTML_FlexyFramework::get();
136 $this->disabled = explode(',', $ff->disable);
138 //$this->fixSequencesPgsql();exit;
141 // ask all the modules to verify the opts
143 $this->checkOpts($opts);
145 if (empty($opts['data-only'])) {
148 if (!empty($opts['only-module-sql'])) {
152 $this->runUpdateModulesData();
155 if (!empty($opts['add-company']) && !in_array('Core', $this->disabled)) {
156 // make sure we have a good cache...?
158 DB_DataObject::factory('companies')->initCompanies($this, $opts);
161 $this->runExtensions();
169 * imports SQL files from all DataObjects directories....
171 * except any matching /migrate/
176 // loop through all the modules, and see if they have a importSQL method?
179 $ff = HTML_Flexyframework::get();
181 $dburl = parse_url($ff->DB_DataObject['database']);
183 //$this->{'import' . $url['scheme']}($url);
185 $dbtype = $dburl['scheme'];
186 $dirmethod = 'import' . $dburl['scheme'] . 'dir';
191 $ar = $this->modulesList();
196 if(in_array($m, $this->disabled)){
197 echo "module $m is disabled \n";
201 echo "Importing SQL from module $m\n";
202 if (!empty($this->opts['only-module-sql']) && $m != $this->opts['only-module-sql']) {
207 // check to see if the class has
211 $file = $this->rootDir. "/Pman/$m/UpdateDatabase.php";
212 if($m != 'Core' && file_exists($file)){
215 $class = "Pman_{$m}_UpdateDatabase";
217 if(method_exists($x, 'importModuleSQL')){
218 echo "Importing SQL from module $m using Module::importModuleSQL\n";
219 $x->opts = $this->opts;
220 $x->rootDir = $this->rootDir;
221 $x->importModuleSQL($dburl);
226 echo "Importing SQL from module $m\n";
229 // if init has been called
231 if (!empty($this->opts['init'])) {
232 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}.init");
238 $fd = $this->rootDir. "/Pman/$m/DataObjects";
240 $this->{$dirmethod}($dburl, $fd);
243 // new -- sql directory..
244 // new style will not support migrate ... they have to go into mysql-migrate.... directories..
245 // new style will not support pg.sql etc.. naming - that's what the direcotries are for..
247 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/sql");
248 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}");
252 if (!empty($this->opts['init']) && file_exists($this->rootDir. "/Pman/$m/{$dbtype}.initdata")) {
253 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
255 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}.initdata");
256 $this->{'fixSequences'. $dbtype}();
268 /** -------------- code to handle importing a whole directory of files into the database ------- **/
271 function importpgsqldir($url, $dir, $disable_triggers = false)
273 $ff = HTML_FlexyFramework::get();
275 require_once 'System.php';
276 $cat = System::which('cat');
277 $psql = System::which('psql');
280 if (!empty($url['pass'])) {
281 putenv("PGPASSWORD=". $url['pass']);
285 ' -h ' . $url['host'] .
286 ' -U' . escapeshellarg($url['user']) .
287 ' ' . basename($url['path']);
290 echo $psql_cmd . "\n" ;
291 echo "scan : $dir\n";
294 $files = array($dir);
299 $files = glob($dir.'/*.sql');
300 uksort($files, 'strcasecmp');
302 //$lsort = create_function('$a,$b','return strlen($a) > strlen($b) ? 1 : -1;');
303 //usort($files, $lsort);
306 foreach($files as $bfn) {
309 if (preg_match('/migrate/i', basename($bfn))) { // skip migration scripts at present..
312 if (preg_match('#\.[a-z]{2}\.sql#i', basename($bfn))
313 && !preg_match('#\.pg\.sql#i', basename($bfn))
314 ) { // skip migration scripts at present..
319 if (!preg_match('/pgsql/', basename($dir) )) {
320 if ( !preg_match('#\.pg\.sql$#', basename($bfn))) {
321 $fn = $this->convertToPG($bfn);
325 // files ending in .pg.sql are native postgres files.. ## depricated
328 $cmd = "$psql_cmd < " . escapeshellarg($fn ? $fn : $bfn) . ' 2>&1' ;
330 echo "$bfn: $cmd ". ($ff->cli ? "\n" : "<BR>\n");
346 * mysql - does not support conversions.
352 function importmysqldir($dburl, $dir)
355 $this->fixMysqlInnodb(); /// run once
357 echo "Import MYSQL :: $dir\n";
360 require_once 'System.php';
361 $cat = System::which('cat');
362 $mysql = System::which('mysql');
366 $mysql_cmd = $mysql .
367 ' -h ' . $dburl['host'] .
368 ' -u' . escapeshellarg($dburl['user']) .
369 (!empty($dburl['pass']) ? ' -p' . escapeshellarg($dburl['pass']) : '') .
370 ' ' . basename($dburl['path']);
371 //echo $mysql_cmd . "\n" ;
373 $files = glob($dir.'/*.sql');
374 uksort($files, 'strcasecmp');
377 foreach($files as $fn) {
380 if (preg_match('/migrate/i', basename($fn))) { // skip migration scripts at present..
383 // .my.sql but not .pg.sql
384 if (preg_match('#\.[a-z]{2}\.sql#i', basename($fn))
385 && !preg_match('#\.my\.sql#i', basename($fn))
386 ) { // skip migration scripts at present..
389 if (!strlen(trim($fn))) {
393 $cmd = "$mysql_cmd -f < " . escapeshellarg($fn) ;
395 echo basename($dir).'/'. basename($fn) . '::' . $cmd. ($this->cli ? "\n" : "<BR>\n");
408 * simple regex based convert mysql to pgsql...
410 function convertToPG($src)
412 //echo "Convert $src\n";
414 $fn = $this->tempName('sql');
416 $ret = array( ); // pad it a bit.
417 $extra = array("", "" );
420 foreach(file($src) as $l) {
423 if (!strlen($l) || $l[0] == '#') {
427 if (preg_match('#create\s+table\s+([a-z0-9_]+)#i', $l, $m)) {
430 if (preg_match('#create\s+table\s+\`([a-z0-9_]+)\`#i', $l, $m)) {
431 $tbl = 'shop_' . strtolower($m[1]);
432 $l = preg_replace('#create\s+table\s+\`([a-z0-9_]+)\`#i', "CREATE TABLE {$tbl}", $l);
434 if (preg_match('#\`([a-z0-9_]+)\`#i', $l, $m) && !preg_match('#alter\s+table\s+#i', $l)) {
435 $l = preg_replace('#\`([a-z0-9_]+)\`#i', "{$m[1]}_name", $l);
438 if ($tbl && preg_match('#auto_increment#i', $l, $m)) {
439 $l = preg_replace('#auto_increment#i', "default nextval('{$tbl}_seq')", $l);
440 $extra[] = "create sequence {$tbl}_seq;";
444 if (preg_match('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', $l, $m)){
445 $l = preg_replace('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', "ALTER TABLE {$tbl}", $l);
448 // enum value -- use the text instead..
450 if ($tbl && preg_match('#([\w]+)\s+(enum\([\w|\W]+\))#i', $l, $m)) {
451 $l = preg_replace('#enum\([\w|\W]+\)#i', "TEXT", $l);
453 // ignore the alter enum
454 if ($tbl && preg_match('#alter\s+table\s+([\w|\W]+)\s+enum\([\w|\W]+\)#i', $l, $m)) {
458 // UNIQUE KEY .. ignore
459 if ($tbl && preg_match('#UNIQUE KEY#i', $l, $m)) {
460 $last = array_pop($ret);
461 $ret[] = trim($last, ",");
465 if ($tbl && preg_match('#RENAME\s+TO#i', $l, $m)) {
469 if ($tbl && preg_match('#change\s+column#i', $l, $m)) {
473 // INDEX lookup ..ignore
474 if ($tbl && preg_match('#INDEX lookup+([\w|\W]+)#i', $l, $m)) {
475 $last = array_pop($ret);
476 $ret[] = trim($last, ",");
481 // CREATE INDEX ..ignore
482 if (preg_match('#alter\s+table\s+([a-z0-9_]+)\s+add\s+index\s+#i', $l, $m)) {
483 // $l = "CREATE INDEX {$m[1]}_{$m[2]} ON {$m[1]} {$m[3]}";
488 $l = preg_replace('#int\([0-9]+\)#i', 'INT', $l);
490 $l = preg_replace('# datetime#i', ' TIMESTAMP WITHOUT TIME ZONE', $l);
491 $l = preg_replace('# blob#i', ' TEXT', $l);
492 $l = preg_replace('# longtext#i', ' TEXT', $l);
493 $l = preg_replace('# tinyint#i', ' INT', $l);
499 $ret = array_merge($extra,$ret);
500 // echo implode("\n", $ret); exit;
502 file_put_contents($fn, implode("\n", $ret));
508 function checkOpts($opts)
512 foreach($opts as $o=>$v) {
513 if (!preg_match('/^json-/', $o) || empty($v)) {
516 if (!file_exists($v)) {
517 die("File does not exist : OPTION --{$o} = {$v} \n");
521 $modules = array_reverse($this->modulesList());
523 // move 'project' one to the end...
525 foreach ($modules as $module){
526 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
527 if($module == 'Core' || !file_exists($file)){
531 $class = "Pman_{$module}_UpdateDatabase";
533 if(!method_exists($x, 'checkOpts')){
536 $x->checkOpts($opts);
540 static function jsonImportFromArray($opts)
542 foreach($opts as $o=>$v) {
543 if (!preg_match('/^json-/', $o) || empty($v)) {
546 $type = str_replace('_', '-', substr($o,5));
548 $data= json_decode(file_get_contents($v),true);
549 $pg = HTML_FlexyFramework::get()->page;
550 DB_DataObject::factory($type)->importFromArray($pg ,$data,$opts);
560 function runUpdateModulesData()
562 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
564 if(!in_array('Core', $this->disabled)){
565 echo "Running jsonImportFromArray\n";
566 Pman_Core_UpdateDatabase::jsonImportFromArray($this->opts);
569 echo "Running updateData on modules\n";
575 $modules = array_reverse($this->modulesList());
577 // move 'project' one to the end...
579 foreach ($modules as $module){
580 if(in_array($module, $this->disabled)){
583 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
584 if($module == 'Core' || !file_exists($file)){
589 $class = "Pman_{$module}_UpdateDatabase";
591 if(!method_exists($x, 'updateData')){
601 function updateDataEnums()
604 $enum = DB_DataObject::Factory('core_enum');
605 //DB_DAtaObject::debugLevel(1);
610 'name' => 'COMPTYPE',
611 'display_name' => 'Company Types',
612 'is_system_enum' => 1,
616 'display_name' => 'Owner',
617 'seqid' => 999, // last...
618 'is_system_enum' => 1,
625 'name' => 'HtmlEditor.font-family',
626 'display_name' => 'HTML Editor font families',
627 'is_system_enum' => 1,
630 'name' => 'Helvetica,Arial,sans-serif',
631 'display_name' => 'Helvetica',
636 'name' => 'Courier New',
637 'display_name' => 'Courier',
642 'display_name' => 'Tahoma',
646 'name' => 'Times New Roman,serif',
647 'display_name' => 'Times',
652 'display_name' => 'Verdana',
664 function updateDataGroups()
667 $groups = DB_DataObject::factory('groups');
668 $groups->initGroups();
670 $groups->initDatabase($this,array(
672 'name' => 'bcc-email', // group who are bcc'ed on all requests.
673 'type' => 0, // system
676 'name' => 'system-email-from',
677 'type' => 0, // system
680 'name' => 'core-person-signup-bcc',
681 'type' => 0, // system
687 function updateDataCompanies()
690 // fix comptypes enums..
691 $c = DB_DataObject::Factory('Companies');
693 $c->selectAdd('distinct(comptype) as comptype');
694 $c->whereAdd("comptype != ''");
697 foreach($c->fetchAll('comptype') as $cts) {
701 $ctb[]= array( 'etype'=>'COMPTYPE', 'name' => $cts, 'display_name' => ucfirst(strtolower($cts)));
704 $c = DB_DataObject::Factory('core_enum');
707 //DB_DataObject::debugLevel(1);
709 $c = DB_DataObject::Factory('Companies');
713 comptype_id = (SELECT id FROM core_enum where etype='comptype' and name=Companies.comptype LIMIT 1)
727 function initEmails($templateDir, $emails)
730 $pg = HTML_FlexyFramework::get()->page;
731 foreach($emails as $name=>$data) {
732 $cm = DB_DataObject::factory('core_email');
733 $update = $cm->get('name', $name);
736 if (empty($cm->bcc_group)) {
737 if (empty($data['bcc_group'])) {
738 $this->jerr("missing bcc_group for template $name");
740 $g = DB_DataObject::Factory('Groups')->lookup('name',$data['bcc_group']);
743 $this->jerr("bcc_group {$data['bcc_group']} does not exist when importing template $name");
745 if (!$g->members('email')) {
746 $this->jerr("bcc_group {$data['bcc_group']} does not have any members");
750 $cm->bcc_group = $g->id;
752 if (empty($cm->test_class)) {
753 if (empty($data['test_class'])) {
754 $this->jerr("missing test_class for template $name");
756 $cm->test_class = $data['test_class'];
758 require_once $cm->test_class . '.php';
760 $clsname = str_replace('/','_', $cm->test_class);
762 $method = new ReflectionMethod($clsname , 'test_'. $name) ;
763 $got_it = $method->isStatic();
764 } catch(Exception $e) {
769 $this->jerr("template {$name} does not have a test method {$clsname}::test_{$name}");
773 echo "email: {$name} - checked\n";
774 continue; /// we do not import the body content of templates that exist...
780 // $basedir = $this->bootLoader->rootDir . $mail_template_dir;
784 'file' => $templateDir. $name .'.html'
787 if (!empty($data['master'])) {
788 $opts['master'] = $templateDir . $master .'.html';
790 require_once 'Pman/Core/Import/Core_email.php';
791 $x = new Pman_Core_Import_Core_email();
794 echo "email: {$name} - CREATED\n";
799 function updateData()
802 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
803 $this->updateDataEnums();
804 $this->updateDataGroups();
805 $this->updateDataCompanies();
807 $c = DB_DataObject::Factory('I18n');
815 function fixMysqlInnodb()
818 static $done_check = false;
822 // innodb in single files is far more efficient that MYD or one big innodb file.
823 // first check if database is using this format.
824 $db = DB_DataObject::factory('core_enum');
825 $db->query("show variables like 'innodb_file_per_table'");
827 if ($db->Value == 'OFF') {
828 die("Error: set innodb_file_per_table = 1 in my.cnf\n\n");
842 /** ------------- schema fixing ... there is an issue with data imported having the wrong sequence names... --- */
844 function fixSequencesMysql()
849 function fixSequencesPgsql()
853 //DB_DataObject::debugLevel(1);
854 $cs = DB_DataObject::factory('core_enum');
858 CASE WHEN strpos(seq_name, '.') > 0 THEN
861 quote_ident(min(schema_name)) ||'.'|| quote_ident(min(seq_name))
864 ||' OWNED BY '|| quote_ident(min(schema_name)) || '.' ||
865 quote_ident(min(table_name)) ||'.'|| quote_ident(min(column_name)) ||';' as cmd
869 n.nspname AS schema_name,
870 c.relname AS table_name,
871 a.attname AS column_name,
872 regexp_replace(regexp_replace(d.adsrc, E'nextval\\\\(+[''\\\"]*', ''),E'[''\\\"]*::.*\$','') AS seq_name
874 JOIN pg_attribute a ON (c.oid=a.attrelid)
875 JOIN pg_attrdef d ON (a.attrelid=d.adrelid AND a.attnum=d.adnum)
876 JOIN pg_namespace n ON (c.relnamespace=n.oid)
877 WHERE has_schema_privilege(n.oid,'USAGE')
878 AND n.nspname NOT LIKE 'pg!_%' escape '!'
879 AND has_table_privilege(c.oid,'SELECT')
880 AND (NOT a.attisdropped)
881 AND d.adsrc ~ '^nextval'
885 CASE WHEN strpos(seq_name, '.') > 0 THEN
886 substring(seq_name, 1,strpos(seq_name,'.')-1)
891 GROUP BY seq_name HAVING count(*)=1
894 while ($cs->fetch()) {
897 foreach($cmds as $cmd) {
898 $cs = DB_DataObject::factory('core_enum');
902 $cs = DB_DataObject::factory('core_enum');
904 SELECT 'SELECT SETVAL(' ||
905 quote_literal(quote_ident(nspname) || '.' || quote_ident(S.relname)) ||
906 ', MAX(' || quote_ident(C.attname)|| ')::integer ) FROM ' || nspname || '.' || quote_ident(T.relname)|| ';' as cmd
912 WHERE S.relkind = 'S'
914 AND D.refobjid = T.oid
915 AND D.refobjid = C.attrelid
916 AND D.refobjsubid = C.attnum
917 AND NS.oid = T.relnamespace
921 while ($cs->fetch()) {
924 foreach($cmds as $cmd) {
925 $cs = DB_DataObject::factory('core_enum');
932 var $extensions = array(
937 function runExtensions()
940 $ff = HTML_Flexyframework::get();
942 $dburl = parse_url($ff->DB_DataObject['database']);
944 $dbtype = $dburl['scheme'];
946 foreach($this->extensions as $ext) {
948 $scls = ucfirst($dbtype). $ext;
949 $cls = __CLASS__ . '_'. $scls;
950 $fn = implode('/',explode('_', $cls)).'.php';
951 if (!file_exists(__DIR__.'/UpdateDatabase/'. $scls .'.php')) {