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();
135 $ff = HTML_FlexyFramework::get();
137 if(!empty($ff->Core_Notify)){
138 // require_once 'Pman/Core/NotifySmtpCheck.php';
139 // $x = new Pman_Core_NotifySmtpCheck();
143 $this->disabled = explode(',', $ff->disable);
145 //$this->fixSequencesPgsql();exit;
148 // ask all the modules to verify the opts
150 $this->checkOpts($opts);
153 // do this first, so the innodb change + utf8 fixes column max sizes
155 // this will trigger errors about freetext indexes - we will have to remove them manually.?
156 // 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..)
158 $this->runExtensions();
161 if (empty($opts['data-only'])) {
164 if (!empty($opts['only-module-sql'])) {
168 $this->runUpdateModulesData();
171 if (!empty($opts['add-company']) && !in_array('Core', $this->disabled)) {
172 // make sure we have a good cache...?
174 DB_DataObject::factory('core_company')->initCompanies($this, $opts);
177 $this->runExtensions();
185 * imports SQL files from all DataObjects directories....
187 * except any matching /migrate/
192 // loop through all the modules, and see if they have a importSQL method?
195 $ff = HTML_Flexyframework::get();
197 $dburl = parse_url($ff->DB_DataObject['database']);
199 //$this->{'import' . $url['scheme']}($url);
201 $dbtype = $dburl['scheme'];
202 $dirmethod = 'import' . $dburl['scheme'] . 'dir';
207 $ar = $this->modulesList();
212 if(in_array($m, $this->disabled)){
213 echo "module $m is disabled \n";
217 echo "Importing SQL from module $m\n";
218 if (!empty($this->opts['only-module-sql']) && $m != $this->opts['only-module-sql']) {
223 // check to see if the class has
227 $file = $this->rootDir. "/Pman/$m/UpdateDatabase.php";
228 if($m != 'Core' && file_exists($file)){
231 $class = "Pman_{$m}_UpdateDatabase";
233 if(method_exists($x, 'importModuleSQL')){
234 echo "Importing SQL from module $m using Module::importModuleSQL\n";
235 $x->opts = $this->opts;
236 $x->rootDir = $this->rootDir;
237 $x->importModuleSQL($dburl);
242 echo "Importing SQL from module $m\n";
245 // if init has been called
247 if (!empty($this->opts['init'])) {
248 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}.init");
254 $fd = $this->rootDir. "/Pman/$m/DataObjects";
256 $this->{$dirmethod}($dburl, $fd);
259 // new -- sql directory..
260 // new style will not support migrate ... they have to go into mysql-migrate.... directories..
261 // new style will not support pg.sql etc.. naming - that's what the direcotries are for..
263 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/sql");
264 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}");
268 if (!empty($this->opts['init']) && file_exists($this->rootDir. "/Pman/$m/{$dbtype}.initdata")) {
269 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
271 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}.initdata");
272 $this->{'fixSequences'. $dbtype}();
284 /** -------------- code to handle importing a whole directory of files into the database ------- **/
287 function importpgsqldir($url, $dir, $disable_triggers = false)
289 $ff = HTML_FlexyFramework::get();
291 require_once 'System.php';
292 $cat = System::which('cat');
293 $psql = System::which('psql');
296 if (!empty($url['pass'])) {
297 putenv("PGPASSWORD=". $url['pass']);
301 ' -h ' . $url['host'] .
302 ' -U' . escapeshellarg($url['user']) .
303 ' ' . basename($url['path']);
306 echo $psql_cmd . "\n" ;
307 echo "scan : $dir\n";
310 $files = array($dir);
315 $files = glob($dir.'/*.sql');
316 uksort($files, 'strcasecmp');
318 //$lsort = create_function('$a,$b','return strlen($a) > strlen($b) ? 1 : -1;');
319 //usort($files, $lsort);
322 foreach($files as $bfn) {
325 if (preg_match('/migrate/i', basename($bfn))) { // skip migration scripts at present..
328 if (preg_match('#\.[a-z]{2}\.sql#i', basename($bfn))
329 && !preg_match('#\.pg\.sql#i', basename($bfn))
330 ) { // skip migration scripts at present..
335 if (!preg_match('/pgsql/', basename($dir) )) {
336 if ( !preg_match('#\.pg\.sql$#', basename($bfn))) {
337 $fn = $this->convertToPG($bfn);
341 // files ending in .pg.sql are native postgres files.. ## depricated
344 $cmd = "$psql_cmd < " . escapeshellarg($fn ? $fn : $bfn) . ' 2>&1' ;
346 echo "$bfn: $cmd ". ($ff->cli ? "\n" : "<BR>\n");
362 * mysql - does not support conversions.
368 function importmysqldir($dburl, $dir)
371 $this->fixMysqlInnodb(); /// run once
373 echo "Import MYSQL :: $dir\n";
376 require_once 'System.php';
377 $cat = System::which('cat');
378 $mysql = System::which('mysql');
382 $mysql_cmd = $mysql .
383 ' -h ' . $dburl['host'] .
384 ' -u' . escapeshellarg($dburl['user']) .
385 (!empty($dburl['pass']) ? ' -p' . escapeshellarg($dburl['pass']) : '') .
386 ' ' . basename($dburl['path']);
387 //echo $mysql_cmd . "\n" ;
389 $files = glob($dir.'/*.sql');
390 uksort($files, 'strcasecmp');
393 foreach($files as $fn) {
396 if (preg_match('/migrate/i', basename($fn))) { // skip migration scripts at present..
399 // .my.sql but not .pg.sql
400 if (preg_match('#\.[a-z]{2}\.sql#i', basename($fn))
401 && !preg_match('#\.my\.sql#i', basename($fn))
402 ) { // skip migration scripts at present..
405 if (!strlen(trim($fn))) {
409 $cmd = "$mysql_cmd -f < " . escapeshellarg($fn) ." 2>&1" ;
411 echo basename($dir).'/'. basename($fn) . '::' . $cmd. ($this->cli ? "\n" : "<BR>\n");
414 $fp = popen($cmd, "r");
417 // send the current file part to the browser
418 $line = trim(fgets($fp, 1024));
423 if (!preg_match('/^ERROR\s+([0-9]+)/', $line, $matches)) {
424 echo " ---- {$line}\n"; flush();
428 switch($matches[1]) {
429 case 1017: // cause by renaming table -- old one does not exist..
430 case 1050: // create tables triggers this..
431 case 1060: // Duplicate column name
432 case 1061: // Duplicate key name - triggered by add index.. but could hide error. - unlikely though.
433 case 1091: // drop index -- name does not exist.. might hide errors..
435 case 1146: // drop a index on an unknown table.. - happens rarely...
436 case 1054: // Unknown column -- triggered by CHANGE COLUMN - but may hide other errrors..
442 echo " ---- {$line}\n"; flush();
446 // 1051: // Unknown table -- normally drop = add iff exists..
447 echo "File: $fn\n$line\n";
463 * simple regex based convert mysql to pgsql...
465 function convertToPG($src)
467 //echo "Convert $src\n";
469 $fn = $this->tempName('sql');
471 $ret = array( ); // pad it a bit.
472 $extra = array("", "" );
475 foreach(file($src) as $l) {
478 if (!strlen($l) || $l[0] == '#') {
482 if (preg_match('#create\s+table\s+([a-z0-9_]+)#i', $l, $m)) {
485 if (preg_match('#create\s+table\s+\`([a-z0-9_]+)\`#i', $l, $m)) {
486 $tbl = 'shop_' . strtolower($m[1]);
487 $l = preg_replace('#create\s+table\s+\`([a-z0-9_]+)\`#i', "CREATE TABLE {$tbl}", $l);
489 if (preg_match('#\`([a-z0-9_]+)\`#i', $l, $m) && !preg_match('#alter\s+table\s+#i', $l)) {
490 $l = preg_replace('#\`([a-z0-9_]+)\`#i', "{$m[1]}_name", $l);
493 if ($tbl && preg_match('#auto_increment#i', $l, $m)) {
494 $l = preg_replace('#auto_increment#i', "default nextval('{$tbl}_seq')", $l);
495 $extra[] = "create sequence {$tbl}_seq;";
499 if (preg_match('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', $l, $m)){
500 $l = preg_replace('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', "ALTER TABLE {$tbl}", $l);
503 // enum value -- use the text instead..
505 if ($tbl && preg_match('#([\w]+)\s+(enum\([\w|\W]+\))#i', $l, $m)) {
506 $l = preg_replace('#enum\([\w|\W]+\)#i', "TEXT", $l);
508 // ignore the alter enum
509 if ($tbl && preg_match('#alter\s+table\s+([\w|\W]+)\s+enum\([\w|\W]+\)#i', $l, $m)) {
513 // UNIQUE KEY .. ignore
514 if ($tbl && preg_match('#UNIQUE KEY#i', $l, $m)) {
515 $last = array_pop($ret);
516 $ret[] = trim($last, ",");
520 if ($tbl && preg_match('#RENAME\s+TO#i', $l, $m)) {
524 if ($tbl && preg_match('#change\s+column#i', $l, $m)) {
528 // INDEX lookup ..ignore
529 if ($tbl && preg_match('#INDEX lookup+([\w|\W]+)#i', $l, $m)) {
530 $last = array_pop($ret);
531 $ret[] = trim($last, ",");
536 // CREATE INDEX ..ignore
537 if (preg_match('#alter\s+table\s+([a-z0-9_]+)\s+add\s+index\s+#i', $l, $m)) {
538 // $l = "CREATE INDEX {$m[1]}_{$m[2]} ON {$m[1]} {$m[3]}";
543 $l = preg_replace('#int\([0-9]+\)#i', 'INT', $l);
545 $l = preg_replace('# datetime#i', ' TIMESTAMP WITHOUT TIME ZONE', $l);
546 $l = preg_replace('# blob#i', ' TEXT', $l);
547 $l = preg_replace('# longtext#i', ' TEXT', $l);
548 $l = preg_replace('# tinyint#i', ' INT', $l);
554 $ret = array_merge($extra,$ret);
555 // echo implode("\n", $ret); exit;
557 file_put_contents($fn, implode("\n", $ret));
563 function checkOpts($opts)
567 foreach($opts as $o=>$v) {
568 if (!preg_match('/^json-/', $o) || empty($v)) {
571 if (!file_exists($v)) {
572 die("File does not exist : OPTION --{$o} = {$v} \n");
576 $modules = array_reverse($this->modulesList());
578 // move 'project' one to the end...
580 foreach ($modules as $module){
581 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
582 if($module == 'Core' || !file_exists($file)){
586 $class = "Pman_{$module}_UpdateDatabase";
588 if(!method_exists($x, 'checkOpts')){
591 $x->checkOpts($opts);
595 static function jsonImportFromArray($opts)
597 foreach($opts as $o=>$v) {
598 if (!preg_match('/^json-/', $o) || empty($v)) {
601 $type = str_replace('_', '-', substr($o,5));
603 $data= json_decode(file_get_contents($v),true);
604 $pg = HTML_FlexyFramework::get()->page;
605 DB_DataObject::factory($type)->importFromArray($pg ,$data,$opts);
615 function runUpdateModulesData()
617 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
619 if(!in_array('Core', $this->disabled)){
620 echo "Running jsonImportFromArray\n";
621 Pman_Core_UpdateDatabase::jsonImportFromArray($this->opts);
624 echo "Running updateData on modules\n";
630 $modules = array_reverse($this->modulesList());
632 // move 'project' one to the end...
634 foreach ($modules as $module){
635 if(in_array($module, $this->disabled)){
638 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
639 if($module == 'Core' || !file_exists($file)){
644 $class = "Pman_{$module}_UpdateDatabase";
646 if(!method_exists($x, 'updateData')){
656 function updateDataEnums()
659 $enum = DB_DataObject::Factory('core_enum');
660 //DB_DAtaObject::debugLevel(1);
665 'name' => 'COMPTYPE',
666 'display_name' => 'Company Types',
667 'is_system_enum' => 1,
671 'display_name' => 'Owner',
672 'seqid' => 999, // last...
673 'is_system_enum' => 1,
680 'name' => 'HtmlEditor.font-family',
681 'display_name' => 'HTML Editor font families',
682 'is_system_enum' => 1,
685 'name' => 'Helvetica,Arial,sans-serif',
686 'display_name' => 'Helvetica',
691 'name' => 'Courier New',
692 'display_name' => 'Courier',
697 'display_name' => 'Tahoma',
701 'name' => 'Times New Roman,serif',
702 'display_name' => 'Times',
707 'display_name' => 'Verdana',
719 function updateDataGroups()
722 $groups = DB_DataObject::factory('core_group');
723 $groups->initGroups();
725 $groups->initDatabase($this,array(
727 'name' => 'bcc-email', // group who are bcc'ed on all requests.
728 'type' => 0, // system
731 'name' => 'system-email-from',
732 'type' => 0, // system
735 'name' => 'core-person-signup-bcc',
736 'type' => 0, // system
742 function updateDataCompanies()
745 // fix comptypes enums..
746 $c = DB_DataObject::Factory('core_company');
748 $c->selectAdd('distinct(comptype) as comptype');
749 $c->whereAdd("comptype != ''");
752 foreach($c->fetchAll('comptype') as $cts) {
756 $ctb[]= array( 'etype'=>'COMPTYPE', 'name' => $cts, 'display_name' => ucfirst(strtolower($cts)));
759 $c = DB_DataObject::Factory('core_enum');
762 //DB_DataObject::debugLevel(1);
764 $c = DB_DataObject::Factory('core_company');
766 UPDATE {$c->tableName()}
768 comptype_id = (SELECT id FROM core_enum where etype='comptype' and name={$c->tableName()}.comptype LIMIT 1)
782 function initEmails($templateDir, $emails)
785 $pg = HTML_FlexyFramework::get()->page;
786 foreach($emails as $name=>$data) {
787 $cm = DB_DataObject::factory('core_email');
788 $update = $cm->get('name', $name);
791 if (empty($cm->bcc_group)) {
792 if (empty($data['bcc_group'])) {
793 $this->jerr("missing bcc_group for template $name");
795 $g = DB_DataObject::Factory('core_group')->lookup('name',$data['bcc_group']);
798 $this->jerr("bcc_group {$data['bcc_group']} does not exist when importing template $name");
802 if (!$g->members('email')) {
803 $this->jerr("bcc_group {$data['bcc_group']} does not have any members");
806 $cm->bcc_group = $g->id;
808 if (empty($cm->test_class)) {
809 if (empty($data['test_class'])) {
810 $this->jerr("missing test_class for template $name");
812 $cm->test_class = $data['test_class'];
814 require_once $cm->test_class . '.php';
816 $clsname = str_replace('/','_', $cm->test_class);
818 $method = new ReflectionMethod($clsname , 'test_'. $name) ;
819 $got_it = $method->isStatic();
820 } catch(Exception $e) {
825 $this->jerr("template {$name} does not have a test method {$clsname}::test_{$name}");
829 echo "email: {$name} - checked\n";
830 continue; /// we do not import the body content of templates that exist...
837 // $basedir = $this->bootLoader->rootDir . $mail_template_dir;
841 'file' => $templateDir. $name .'.html'
844 if (!empty($data['master'])) {
845 $opts['master'] = $templateDir . $master .'.html';
847 require_once 'Pman/Core/Import/Core_email.php';
848 $x = new Pman_Core_Import_Core_email();
849 $x->updateOrCreateEmail('', $opts, $cm);
851 echo "email: {$name} - CREATED\n";
856 function updateData()
859 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
860 $this->updateDataEnums();
861 $this->updateDataGroups();
862 $this->updateDataCompanies();
864 $c = DB_DataObject::Factory('I18n');
872 function fixMysqlInnodb()
875 static $done_check = false;
879 // innodb in single files is far more efficient that MYD or one big innodb file.
880 // first check if database is using this format.
881 $db = DB_DataObject::factory('core_enum');
882 $db->query("show variables like 'innodb_file_per_table'");
884 if ($db->Value == 'OFF') {
885 die("Error: set innodb_file_per_table = 1 in my.cnf\n\n");
888 $db = DB_DataObject::factory('core_enum');
889 $db->query("select version() as version");
892 if (version_compare($db->version, '5.7', '>=' )) {
894 $db = DB_DataObject::factory('core_enum');
895 $db->query("show variables like 'sql_mode'");
898 $modes = explode(",", $db->Value);
900 // these are 'new' problems with mysql.
902 in_array('NO_ZERO_IN_DATE', $modes) ||
903 in_array('NO_ZERO_DATE', $modes) ||
904 in_array('STRICT_TRANS_TABLES', $modes) ||
905 !in_array('ALLOW_INVALID_DATES', $modes)
907 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");
922 /** ------------- schema fixing ... there is an issue with data imported having the wrong sequence names... --- */
924 function fixSequencesMysql()
929 function fixSequencesPgsql()
933 //DB_DataObject::debugLevel(1);
934 $cs = DB_DataObject::factory('core_enum');
938 CASE WHEN strpos(seq_name, '.') > 0 THEN
941 quote_ident(min(schema_name)) ||'.'|| quote_ident(min(seq_name))
944 ||' OWNED BY '|| quote_ident(min(schema_name)) || '.' ||
945 quote_ident(min(table_name)) ||'.'|| quote_ident(min(column_name)) ||';' as cmd
949 n.nspname AS schema_name,
950 c.relname AS table_name,
951 a.attname AS column_name,
952 regexp_replace(regexp_replace(d.adsrc, E'nextval\\\\(+[''\\\"]*', ''),E'[''\\\"]*::.*\$','') AS seq_name
954 JOIN pg_attribute a ON (c.oid=a.attrelid)
955 JOIN pg_attrdef d ON (a.attrelid=d.adrelid AND a.attnum=d.adnum)
956 JOIN pg_namespace n ON (c.relnamespace=n.oid)
957 WHERE has_schema_privilege(n.oid,'USAGE')
958 AND n.nspname NOT LIKE 'pg!_%' escape '!'
959 AND has_table_privilege(c.oid,'SELECT')
960 AND (NOT a.attisdropped)
961 AND d.adsrc ~ '^nextval'
965 CASE WHEN strpos(seq_name, '.') > 0 THEN
966 substring(seq_name, 1,strpos(seq_name,'.')-1)
971 GROUP BY seq_name HAVING count(*)=1
974 while ($cs->fetch()) {
977 foreach($cmds as $cmd) {
978 $cs = DB_DataObject::factory('core_enum');
982 $cs = DB_DataObject::factory('core_enum');
984 SELECT 'SELECT SETVAL(' ||
985 quote_literal(quote_ident(nspname) || '.' || quote_ident(S.relname)) ||
986 ', MAX(' || quote_ident(C.attname)|| ')::integer ) FROM ' || nspname || '.' || quote_ident(T.relname)|| ';' as cmd
992 WHERE S.relkind = 'S'
994 AND D.refobjid = T.oid
995 AND D.refobjid = C.attrelid
996 AND D.refobjsubid = C.attnum
997 AND NS.oid = T.relnamespace
1001 while ($cs->fetch()) {
1004 foreach($cmds as $cmd) {
1005 $cs = DB_DataObject::factory('core_enum');
1012 var $extensions = array(
1017 function runExtensions()
1020 $ff = HTML_Flexyframework::get();
1022 $dburl = parse_url($ff->DB_DataObject['database']);
1024 $dbtype = $dburl['scheme'];
1026 foreach($this->extensions as $ext) {
1028 $scls = ucfirst($dbtype). $ext;
1029 $cls = __CLASS__ . '_'. $scls;
1030 $fn = implode('/',explode('_', $cls)).'.php';
1031 if (!file_exists(__DIR__.'/UpdateDatabase/'. $scls .'.php')) {
1042 function checkSystem()
1044 // most of these are from File_Convert...
1046 // these are required - and have simple dependancies.
1047 require_once 'System.php';
1053 'rsvg-convert', //librsvg2-bin
1059 // these are prefered - but may have complicated depenacies
1064 'html2text', // not availabe in debian squeeze
1065 'pdftocairo', //poppler-utils - not available in debian squeeze.
1075 foreach($req as $r) {
1076 if (!System::which($r)) {
1082 $this->jerr("Missing these programs - need installing\n" . implode("\n",$res));
1084 foreach($pref as $r) {
1085 if (!System::which($r)) {
1091 echo "WARNING: Missing these programs - they may need installing\n". implode("\n",$res);