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',
71 'json-person' => array(
72 'desc' => 'Person JSON file',
80 static function cli_opts()
83 $ret = self::$cli_opts;
84 $ff = HTML_FlexyFramework::get();
86 $mods = $a->modulesList();
87 foreach($mods as $m) {
89 $fd = $ff->rootDir. "/Pman/$m/UpdateDatabase.php";
90 if (!file_exists($fd)) {
96 $cls = new ReflectionClass('Pman_'. $m . '_UpdateDatabase');
98 $ret = array_merge($ret, $cls->getStaticPropertyValue('cli_opts'));
107 var $disabled = array();
114 $ff = HTML_FlexyFramework::get();
115 if (!empty($ff->cli)) {
120 parent::getAuth(); // load company!
121 $au = $this->getAuthUser();
122 if (!$au || $au->company()->comptype != 'OWNER') {
123 $this->jerr("Not authenticated", array('authFailure' => true));
125 $this->authUser = $au;
129 function get($args, $opts)
131 PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, array($this, 'onPearError'));
133 $this->checkSystem();
136 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
138 $ff = HTML_FlexyFramework::get();
140 if(!empty($ff->Core_Notify)){
141 // require_once 'Pman/Core/NotifySmtpCheck.php';
142 // $x = new Pman_Core_NotifySmtpCheck();
146 $this->disabled = explode(',', $ff->disable);
148 //$this->fixSequencesPgsql();exit;
151 // ask all the modules to verify the opts
153 $this->checkOpts($opts);
156 // do this first, so the innodb change + utf8 fixes column max sizes
158 // this will trigger errors about freetext indexes - we will have to remove them manually.?
159 // otherwise we need to do an sql query to find them, then remove them (not really worth it as it only affects really old code..)
161 $this->runExtensions();
164 if (empty($opts['data-only'])) {
167 if (!empty($opts['only-module-sql'])) {
171 $this->runUpdateModulesData();
174 if (!empty($opts['add-company']) && !in_array('Core', $this->disabled)) {
175 // make sure we have a good cache...?
177 DB_DataObject::factory('core_company')->initCompanies($this, $opts);
180 $this->runExtensions();
188 * imports SQL files from all DataObjects directories....
190 * except any matching /migrate/
195 // loop through all the modules, and see if they have a importSQL method?
198 $ff = HTML_Flexyframework::get();
200 $dburl = parse_url($ff->DB_DataObject['database']);
202 //$this->{'import' . $url['scheme']}($url);
204 $dbtype = $dburl['scheme'];
205 $dirmethod = 'import' . $dburl['scheme'] . 'dir';
210 $ar = $this->modulesList();
215 if(in_array($m, $this->disabled)){
216 echo "module $m is disabled \n";
220 echo "Importing SQL from module $m\n";
221 if (!empty($this->opts['only-module-sql']) && $m != $this->opts['only-module-sql']) {
226 // check to see if the class has
230 $file = $this->rootDir. "/Pman/$m/UpdateDatabase.php";
231 if($m != 'Core' && file_exists($file)){
234 $class = "Pman_{$m}_UpdateDatabase";
236 if(method_exists($x, 'importModuleSQL')){
237 echo "Importing SQL from module $m using Module::importModuleSQL\n";
238 $x->opts = $this->opts;
239 $x->rootDir = $this->rootDir;
240 $x->importModuleSQL($dburl);
245 echo "Importing SQL from module $m\n";
248 // if init has been called
250 if (!empty($this->opts['init'])) {
251 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}.init");
257 $fd = $this->rootDir. "/Pman/$m/DataObjects";
259 $this->{$dirmethod}($dburl, $fd);
262 // new -- sql directory..
263 // new style will not support migrate ... they have to go into mysql-migrate.... directories..
264 // new style will not support pg.sql etc.. naming - that's what the direcotries are for..
266 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/sql");
267 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}");
271 if (!empty($this->opts['init']) && file_exists($this->rootDir. "/Pman/$m/{$dbtype}.initdata")) {
272 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
274 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}.initdata");
275 $this->{'fixSequences'. $dbtype}();
287 /** -------------- code to handle importing a whole directory of files into the database ------- **/
290 function importpgsqldir($url, $dir, $disable_triggers = false)
292 $ff = HTML_FlexyFramework::get();
294 require_once 'System.php';
295 $cat = System::which('cat');
296 $psql = System::which('psql');
299 if (!empty($url['pass'])) {
300 putenv("PGPASSWORD=". $url['pass']);
304 ' -h ' . $url['host'] .
305 ' -U' . escapeshellarg($url['user']) .
306 ' ' . basename($url['path']);
309 echo $psql_cmd . "\n" ;
310 echo "scan : $dir\n";
313 $files = array($dir);
318 $files = glob($dir.'/*.sql');
319 uksort($files, 'strcasecmp');
321 //$lsort = create_function('$a,$b','return strlen($a) > strlen($b) ? 1 : -1;');
322 //usort($files, $lsort);
325 foreach($files as $bfn) {
328 if (preg_match('/migrate/i', basename($bfn))) { // skip migration scripts at present..
331 if (preg_match('#\.[a-z]{2}\.sql#i', basename($bfn))
332 && !preg_match('#\.pg\.sql#i', basename($bfn))
333 ) { // skip migration scripts at present..
338 if (!preg_match('/pgsql/', basename($dir) )) {
339 if ( !preg_match('#\.pg\.sql$#', basename($bfn))) {
340 $fn = $this->convertToPG($bfn);
344 // files ending in .pg.sql are native postgres files.. ## depricated
347 $cmd = "$psql_cmd < " . escapeshellarg($fn ? $fn : $bfn) . ' 2>&1' ;
349 echo "$bfn: $cmd ". ($ff->cli ? "\n" : "<BR>\n");
365 * mysql - does not support conversions.
371 function importmysqldir($dburl, $dir)
374 $this->fixMysqlInnodb(); /// run once
376 echo "Import MYSQL :: $dir\n";
379 require_once 'System.php';
380 $cat = System::which('cat');
381 $mysql = System::which('mysql');
385 $mysql_cmd = $mysql .
386 ' -h ' . $dburl['host'] .
387 ' -u' . escapeshellarg($dburl['user']) .
388 (!empty($dburl['pass']) ? ' -p' . escapeshellarg($dburl['pass']) : '') .
389 ' ' . basename($dburl['path']);
390 //echo $mysql_cmd . "\n" ;
392 $files = glob($dir.'/*.sql');
393 uksort($files, 'strcasecmp');
396 foreach($files as $fn) {
399 if (preg_match('/migrate/i', basename($fn))) { // skip migration scripts at present..
402 // .my.sql but not .pg.sql
403 if (preg_match('#\.[a-z]{2}\.sql#i', basename($fn))
404 && !preg_match('#\.my\.sql#i', basename($fn))
405 ) { // skip migration scripts at present..
408 if (!strlen(trim($fn))) {
412 $cmd = "$mysql_cmd -f < " . escapeshellarg($fn) ." 2>&1" ;
414 echo basename($dir).'/'. basename($fn) . '::' . $cmd. ($this->cli ? "\n" : "<BR>\n");
417 $fp = popen($cmd, "r");
420 // send the current file part to the browser
421 $line = trim(fgets($fp, 1024));
426 if (!preg_match('/^ERROR\s+([0-9]+)/', $line, $matches)) {
427 echo " ---- {$line}\n"; flush();
431 switch($matches[1]) {
432 case 1017: // cause by renaming table -- old one does not exist..
433 case 1050: // create tables triggers this..
434 case 1060: // Duplicate column name
435 case 1061: // Duplicate key name - triggered by add index.. but could hide error. - unlikely though.
436 case 1091: // drop index -- name does not exist.. might hide errors..
438 case 1146: // drop a index on an unknown table.. - happens rarely...
439 case 1054: // Unknown column -- triggered by CHANGE COLUMN - but may hide other errrors..
445 echo " ---- {$line}\n"; flush();
449 // 1051: // Unknown table -- normally drop = add iff exists..
450 echo "File: $fn\n$line\n";
466 * simple regex based convert mysql to pgsql...
468 function convertToPG($src)
470 //echo "Convert $src\n";
472 $fn = $this->tempName('sql');
474 $ret = array( ); // pad it a bit.
475 $extra = array("", "" );
478 foreach(file($src) as $l) {
481 if (!strlen($l) || $l[0] == '#') {
485 if (preg_match('#create\s+table\s+([a-z0-9_]+)#i', $l, $m)) {
488 if (preg_match('#create\s+table\s+\`([a-z0-9_]+)\`#i', $l, $m)) {
489 $tbl = 'shop_' . strtolower($m[1]);
490 $l = preg_replace('#create\s+table\s+\`([a-z0-9_]+)\`#i', "CREATE TABLE {$tbl}", $l);
492 if (preg_match('#\`([a-z0-9_]+)\`#i', $l, $m) && !preg_match('#alter\s+table\s+#i', $l)) {
493 $l = preg_replace('#\`([a-z0-9_]+)\`#i', "{$m[1]}_name", $l);
496 if ($tbl && preg_match('#auto_increment#i', $l, $m)) {
497 $l = preg_replace('#auto_increment#i', "default nextval('{$tbl}_seq')", $l);
498 $extra[] = "create sequence {$tbl}_seq;";
502 if (preg_match('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', $l, $m)){
503 $l = preg_replace('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', "ALTER TABLE {$tbl}", $l);
506 // enum value -- use the text instead..
508 if ($tbl && preg_match('#([\w]+)\s+(enum\([\w|\W]+\))#i', $l, $m)) {
509 $l = preg_replace('#enum\([\w|\W]+\)#i', "TEXT", $l);
511 // ignore the alter enum
512 if ($tbl && preg_match('#alter\s+table\s+([\w|\W]+)\s+enum\([\w|\W]+\)#i', $l, $m)) {
516 // UNIQUE KEY .. ignore
517 if ($tbl && preg_match('#UNIQUE KEY#i', $l, $m)) {
518 $last = array_pop($ret);
519 $ret[] = trim($last, ",");
523 if ($tbl && preg_match('#RENAME\s+TO#i', $l, $m)) {
527 if ($tbl && preg_match('#change\s+column#i', $l, $m)) {
531 // INDEX lookup ..ignore
532 if ($tbl && preg_match('#INDEX lookup+([\w|\W]+)#i', $l, $m)) {
533 $last = array_pop($ret);
534 $ret[] = trim($last, ",");
539 // CREATE INDEX ..ignore
540 if (preg_match('#alter\s+table\s+([a-z0-9_]+)\s+add\s+index\s+#i', $l, $m)) {
541 // $l = "CREATE INDEX {$m[1]}_{$m[2]} ON {$m[1]} {$m[3]}";
546 $l = preg_replace('#int\([0-9]+\)#i', 'INT', $l);
548 $l = preg_replace('# datetime#i', ' TIMESTAMP WITHOUT TIME ZONE', $l);
549 $l = preg_replace('# blob#i', ' TEXT', $l);
550 $l = preg_replace('# longtext#i', ' TEXT', $l);
551 $l = preg_replace('# tinyint#i', ' INT', $l);
557 $ret = array_merge($extra,$ret);
558 // echo implode("\n", $ret); exit;
560 file_put_contents($fn, implode("\n", $ret));
566 function checkOpts($opts)
570 foreach($opts as $o=>$v) {
571 if (!preg_match('/^json-/', $o) || empty($v)) {
574 if (!file_exists($v)) {
575 die("File does not exist : OPTION --{$o} = {$v} \n");
579 $modules = array_reverse($this->modulesList());
581 // move 'project' one to the end...
583 foreach ($modules as $module){
584 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
585 if($module == 'Core' || !file_exists($file)){
589 $class = "Pman_{$module}_UpdateDatabase";
591 if(!method_exists($x, 'checkOpts')){
594 $x->checkOpts($opts);
598 static function jsonImportFromArray($opts)
600 foreach($opts as $o=>$v) {
601 if (!preg_match('/^json-/', $o) || empty($v)) {
604 $type = str_replace('_', '-', substr($o,5));
606 $data= json_decode(file_get_contents($v),true);
607 $pg = HTML_FlexyFramework::get()->page;
608 DB_DataObject::factory($type)->importFromArray($pg ,$data,$opts);
618 function runUpdateModulesData()
620 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
622 if(!in_array('Core', $this->disabled)){
623 echo "Running jsonImportFromArray\n";
624 Pman_Core_UpdateDatabase::jsonImportFromArray($this->opts);
627 echo "Running updateData on modules\n";
633 $modules = array_reverse($this->modulesList());
635 // move 'project' one to the end...
637 foreach ($modules as $module){
638 if(in_array($module, $this->disabled)){
641 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
642 if($module == 'Core' || !file_exists($file)){
647 $class = "Pman_{$module}_UpdateDatabase";
649 if(!method_exists($x, 'updateData')){
659 function updateDataEnums()
662 $enum = DB_DataObject::Factory('core_enum');
663 //DB_DAtaObject::debugLevel(1);
668 'name' => 'COMPTYPE',
669 'display_name' => 'Company Types',
670 'is_system_enum' => 1,
674 'display_name' => 'Owner',
675 'seqid' => 999, // last...
676 'is_system_enum' => 1,
683 'name' => 'HtmlEditor.font-family',
684 'display_name' => 'HTML Editor font families',
685 'is_system_enum' => 1,
688 'name' => 'Helvetica,Arial,sans-serif',
689 'display_name' => 'Helvetica',
694 'name' => 'Courier New',
695 'display_name' => 'Courier',
700 'display_name' => 'Tahoma',
704 'name' => 'Times New Roman,serif',
705 'display_name' => 'Times',
710 'display_name' => 'Verdana',
722 function updateDataGroups()
725 $groups = DB_DataObject::factory('core_group');
726 $groups->initGroups();
728 $groups->initDatabase($this,array(
730 'name' => 'bcc-email', // group who are bcc'ed on all requests.
731 'type' => 0, // system
734 'name' => 'system-email-from',
735 'type' => 0, // system
738 'name' => 'core-person-signup-bcc',
739 'type' => 0, // system
745 function updateDataCompanies()
748 // fix comptypes enums..
749 $c = DB_DataObject::Factory('core_company');
751 $c->selectAdd('distinct(comptype) as comptype');
752 $c->whereAdd("comptype != ''");
755 foreach($c->fetchAll('comptype') as $cts) {
759 $ctb[]= array( 'etype'=>'COMPTYPE', 'name' => $cts, 'display_name' => ucfirst(strtolower($cts)));
762 $c = DB_DataObject::Factory('core_enum');
765 //DB_DataObject::debugLevel(1);
767 $c = DB_DataObject::Factory('core_company');
769 UPDATE {$c->tableName()}
771 comptype_id = (SELECT id FROM core_enum where etype='comptype' and name={$c->tableName()}.comptype LIMIT 1)
785 function initEmails($templateDir, $emails)
788 $pg = HTML_FlexyFramework::get()->page;
789 foreach($emails as $name=>$data) {
790 $cm = DB_DataObject::factory('core_email');
791 $update = $cm->get('name', $name);
794 if (empty($cm->bcc_group)) {
795 if (empty($data['bcc_group'])) {
796 $this->jerr("missing bcc_group for template $name");
798 $g = DB_DataObject::Factory('core_group')->lookup('name',$data['bcc_group']);
801 $this->jerr("bcc_group {$data['bcc_group']} does not exist when importing template $name");
805 if (!$g->members('email')) {
806 $this->jerr("bcc_group {$data['bcc_group']} does not have any members");
809 $cm->bcc_group = $g->id;
811 if (empty($cm->test_class)) {
812 if (empty($data['test_class'])) {
813 $this->jerr("missing test_class for template $name");
815 $cm->test_class = $data['test_class'];
817 require_once $cm->test_class . '.php';
819 $clsname = str_replace('/','_', $cm->test_class);
821 $method = new ReflectionMethod($clsname , 'test_'. $name) ;
822 $got_it = $method->isStatic();
823 } catch(Exception $e) {
828 $this->jerr("template {$name} does not have a test method {$clsname}::test_{$name}");
832 echo "email: {$name} - checked\n";
833 continue; /// we do not import the body content of templates that exist...
840 // $basedir = $this->bootLoader->rootDir . $mail_template_dir;
844 'file' => $templateDir. $name .'.html'
847 if (!empty($data['master'])) {
848 $opts['master'] = $templateDir . $master .'.html';
850 require_once 'Pman/Core/Import/Core_email.php';
851 $x = new Pman_Core_Import_Core_email();
852 $x->updateOrCreateEmail('', $opts, $cm);
854 echo "email: {$name} - CREATED\n";
859 function updateData()
862 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
863 $this->updateDataEnums();
864 $this->updateDataGroups();
865 $this->updateDataCompanies();
867 $c = DB_DataObject::Factory('I18n');
875 function fixMysqlInnodb()
878 static $done_check = false;
882 // innodb in single files is far more efficient that MYD or one big innodb file.
883 // first check if database is using this format.
884 $db = DB_DataObject::factory('core_enum');
885 $db->query("show variables like 'innodb_file_per_table'");
887 if ($db->Value == 'OFF') {
888 die("Error: set innodb_file_per_table = 1 in my.cnf\n\n");
891 $db = DB_DataObject::factory('core_enum');
892 $db->query("select version() as version");
895 if (version_compare($db->version, '5.7', '>=' )) {
897 $db = DB_DataObject::factory('core_enum');
898 $db->query("show variables like 'sql_mode'");
901 $modes = explode(",", $db->Value);
903 // these are 'new' problems with mysql.
905 in_array('NO_ZERO_IN_DATE', $modes) ||
906 in_array('NO_ZERO_DATE', $modes) ||
907 in_array('STRICT_TRANS_TABLES', $modes) ||
908 !in_array('ALLOW_INVALID_DATES', $modes)
910 die("Error: set sql_mode include 'ALLOW_INVALID_DATES', remove 'NO_ZERO_IN_DATE' AND 'STRICT_TRANS_TABLES' AND 'NO_ZERO_DATE' in my.cnf\n\n");
925 /** ------------- schema fixing ... there is an issue with data imported having the wrong sequence names... --- */
927 function fixSequencesMysql()
932 function fixSequencesPgsql()
936 //DB_DataObject::debugLevel(1);
937 $cs = DB_DataObject::factory('core_enum');
941 CASE WHEN strpos(seq_name, '.') > 0 THEN
944 quote_ident(min(schema_name)) ||'.'|| quote_ident(min(seq_name))
947 ||' OWNED BY '|| quote_ident(min(schema_name)) || '.' ||
948 quote_ident(min(table_name)) ||'.'|| quote_ident(min(column_name)) ||';' as cmd
952 n.nspname AS schema_name,
953 c.relname AS table_name,
954 a.attname AS column_name,
955 regexp_replace(regexp_replace(d.adsrc, E'nextval\\\\(+[''\\\"]*', ''),E'[''\\\"]*::.*\$','') AS seq_name
957 JOIN pg_attribute a ON (c.oid=a.attrelid)
958 JOIN pg_attrdef d ON (a.attrelid=d.adrelid AND a.attnum=d.adnum)
959 JOIN pg_namespace n ON (c.relnamespace=n.oid)
960 WHERE has_schema_privilege(n.oid,'USAGE')
961 AND n.nspname NOT LIKE 'pg!_%' escape '!'
962 AND has_table_privilege(c.oid,'SELECT')
963 AND (NOT a.attisdropped)
964 AND d.adsrc ~ '^nextval'
968 CASE WHEN strpos(seq_name, '.') > 0 THEN
969 substring(seq_name, 1,strpos(seq_name,'.')-1)
974 GROUP BY seq_name HAVING count(*)=1
977 while ($cs->fetch()) {
980 foreach($cmds as $cmd) {
981 $cs = DB_DataObject::factory('core_enum');
985 $cs = DB_DataObject::factory('core_enum');
987 SELECT 'SELECT SETVAL(' ||
988 quote_literal(quote_ident(nspname) || '.' || quote_ident(S.relname)) ||
989 ', MAX(' || quote_ident(C.attname)|| ')::integer ) FROM ' || nspname || '.' || quote_ident(T.relname)|| ';' as cmd
995 WHERE S.relkind = 'S'
997 AND D.refobjid = T.oid
998 AND D.refobjid = C.attrelid
999 AND D.refobjsubid = C.attnum
1000 AND NS.oid = T.relnamespace
1004 while ($cs->fetch()) {
1007 foreach($cmds as $cmd) {
1008 $cs = DB_DataObject::factory('core_enum');
1015 var $extensions = array(
1020 function runExtensions()
1023 $ff = HTML_Flexyframework::get();
1025 $dburl = parse_url($ff->DB_DataObject['database']);
1027 $dbtype = $dburl['scheme'];
1029 foreach($this->extensions as $ext) {
1031 $scls = ucfirst($dbtype). $ext;
1032 $cls = __CLASS__ . '_'. $scls;
1033 $fn = implode('/',explode('_', $cls)).'.php';
1034 if (!file_exists(__DIR__.'/UpdateDatabase/'. $scls .'.php')) {
1045 function checkSystem()
1047 // most of these are from File_Convert...
1049 // these are required - and have simple dependancies.
1050 require_once 'System.php';
1056 'rsvg-convert', //librsvg2-bin
1062 // these are prefered - but may have complicated depenacies
1067 'html2text', // not availabe in debian squeeze
1068 'pdftocairo', //poppler-utils - not available in debian squeeze.
1078 foreach($req as $r) {
1079 if (!System::which($r)) {
1085 $this->jerr("Missing these programs - need installing\n" . implode("\n",$res));
1087 foreach($pref as $r) {
1088 if (!System::which($r)) {
1094 echo "WARNING: Missing these programs - they may need installing\n". implode("\n",$res);