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=array())
131 PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, array($this, 'onPearError'));
133 $this->checkSystem();
135 if (class_exists('PDO_DataObjects_Introspection')) {
136 PDO_DataObject_Introspection::$cache = array();
139 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
141 $ff = HTML_FlexyFramework::get();
143 if(!isset($ff->Pman) || !isset($ff->Pman['local_base_url'])){
144 die("Please setup local_base_url");
149 if(!empty($ff->Core_Notify)){
150 // require_once 'Pman/Core/NotifySmtpCheck.php';
151 // $x = new Pman_Core_NotifySmtpCheck();
155 $this->disabled = explode(',', $ff->disable);
157 //$this->fixSequencesPgsql();exit;
160 // ask all the modules to verify the opts
162 $this->checkOpts($opts);
165 // do this first, so the innodb change + utf8 fixes column max sizes
167 // this will trigger errors about freetext indexes - we will have to remove them manually.?
168 // 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..)
170 $this->runExtensions();
173 if (empty($opts['data-only'])) {
176 if (!empty($opts['only-module-sql'])) {
180 $this->runUpdateModulesData();
183 if (!empty($opts['add-company']) && !in_array('Core', $this->disabled)) {
184 // make sure we have a good cache...?
186 DB_DataObject::factory('core_company')->initCompanies($this, $opts);
189 $this->runExtensions();
197 * imports SQL files from all DataObjects directories....
199 * except any matching /migrate/
204 // loop through all the modules, and see if they have a importSQL method?
207 $ff = HTML_Flexyframework::get();
209 $dburl = parse_url($ff->database); // used to be DB_DataObject['database'] - but not portable to PDO
211 //$this->{'import' . $url['scheme']}($url);
213 $dbtype = $dburl['scheme'];
216 $dirmethod = 'import' . $dburl['scheme'] . 'dir';
221 $ar = $this->modulesList();
226 if(in_array($m, $this->disabled)){
227 echo "module $m is disabled \n";
231 echo "Importing SQL from module $m\n";
232 if (!empty($this->opts['only-module-sql']) && $m != $this->opts['only-module-sql']) {
237 // check to see if the class has
241 $file = $this->rootDir. "/Pman/$m/UpdateDatabase.php";
242 if($m != 'Core' && file_exists($file)){
245 $class = "Pman_{$m}_UpdateDatabase";
247 if(method_exists($x, 'importModuleSQL')){
248 echo "Importing SQL from module $m using Module::importModuleSQL\n";
249 $x->opts = $this->opts;
250 $x->rootDir = $this->rootDir;
251 $x->importModuleSQL($dburl);
256 echo "Importing SQL from module $m\n";
259 // if init has been called
261 if (!empty($this->opts['init'])) {
262 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}.init");
268 $fd = $this->rootDir. "/Pman/$m/DataObjects";
270 $this->{$dirmethod}($dburl, $fd);
273 // new -- sql directory..
274 // new style will not support migrate ... they have to go into mysql-migrate.... directories..
275 // new style will not support pg.sql etc.. naming - that's what the direcotries are for..
277 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/sql");
278 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}");
282 if (!empty($this->opts['init']) && file_exists($this->rootDir. "/Pman/$m/{$dbtype}.initdata")) {
283 if (class_exists('PDO_DataObjects_Introspection')) {
284 PDO_DataObject_Introspection::$cache = array();
286 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
288 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}.initdata");
289 $this->{'fixSequences'. $dbtype}();
302 /** -------------- code to handle importing a whole directory of files into the database ------- **/
305 function importpgsqldir($url, $dir, $disable_triggers = false)
307 $ff = HTML_FlexyFramework::get();
309 require_once 'System.php';
310 $cat = System::which('cat');
311 $psql = System::which('psql');
314 if (!empty($url['pass'])) {
315 putenv("PGPASSWORD=". $url['pass']);
319 ' -h ' . $url['host'] .
320 ' -U' . escapeshellarg($url['user']) .
321 ' ' . basename($url['path']);
324 echo $psql_cmd . "\n" ;
325 echo "scan : $dir\n";
328 $files = array($dir);
333 $files = glob($dir.'/*.sql');
334 uksort($files, 'strcasecmp');
336 //$lsort = create_function('$a,$b','return strlen($a) > strlen($b) ? 1 : -1;');
337 //usort($files, $lsort);
340 foreach($files as $bfn) {
343 if (preg_match('/migrate/i', basename($bfn))) { // skip migration scripts at present..
346 if (preg_match('#\.[a-z]{2}\.sql#i', basename($bfn))
347 && !preg_match('#\.pg\.sql#i', basename($bfn))
348 ) { // skip migration scripts at present..
353 if (!preg_match('/pgsql/', basename($dir) )) {
354 if ( !preg_match('#\.pg\.sql$#', basename($bfn))) {
355 $fn = $this->convertToPG($bfn);
359 // files ending in .pg.sql are native postgres files.. ## depricated
362 $cmd = "$psql_cmd < " . escapeshellarg($fn ? $fn : $bfn) . ' 2>&1' ;
364 echo "$bfn: $cmd ". ($ff->cli ? "\n" : "<BR>\n");
380 * mysql - does not support conversions.
384 function importmysqlidir($dburl, $dir) {
385 return $this->importmysqldir($dburl, $dir);
388 function importmysqldir($dburl, $dir)
391 $this->fixMysqlInnodb(); /// run once
393 echo "Import MYSQL :: $dir\n";
396 require_once 'System.php';
397 $cat = System::which('cat');
398 $mysql = System::which('mysql');
402 $mysql_cmd = $mysql .
403 ' -h ' . $dburl['host'] .
404 ' -u' . escapeshellarg($dburl['user']) .
405 (!empty($dburl['pass']) ? ' -p' . escapeshellarg($dburl['pass']) : '') .
406 ' ' . basename($dburl['path']);
407 //echo $mysql_cmd . "\n" ;
409 $files = glob($dir.'/*.sql');
410 uksort($files, 'strcasecmp');
413 foreach($files as $fn) {
416 if (preg_match('/migrate/i', basename($fn))) { // skip migration scripts at present..
419 // .my.sql but not .pg.sql
420 if (preg_match('#\.[a-z]{2}\.sql#i', basename($fn))
421 && !preg_match('#\.my\.sql#i', basename($fn))
422 ) { // skip migration scripts at present..
425 if (!strlen(trim($fn))) {
429 $cmd = "$mysql_cmd -f < " . escapeshellarg($fn) ." 2>&1" ;
431 echo basename($dir).'/'. basename($fn) . '::' . $cmd. ($this->cli ? "\n" : "<BR>\n");
434 $fp = popen($cmd, "r");
437 // send the current file part to the browser
438 $line = trim(fgets($fp, 1024));
443 if (!preg_match('/^ERROR\s+([0-9]+)/', $line, $matches)) {
444 echo " ---- {$line}\n"; flush();
448 switch($matches[1]) {
449 case 1017: // cause by renaming table -- old one does not exist..
450 case 1050: // create tables triggers this..
451 case 1060: // Duplicate column name
452 case 1061: // Duplicate key name - triggered by add index.. but could hide error. - unlikely though.
453 case 1091: // drop index -- name does not exist.. might hide errors..
455 case 1146: // drop a index on an unknown table.. - happens rarely...
456 case 1054: // Unknown column -- triggered by CHANGE COLUMN - but may hide other errrors..
462 echo " ---- {$line}\n"; flush();
466 // 1051: // Unknown table -- normally drop = add iff exists..
467 echo "File: $fn\n$line\n";
483 * simple regex based convert mysql to pgsql...
485 function convertToPG($src)
487 //echo "Convert $src\n";
489 $fn = $this->tempName('sql');
491 $ret = array( ); // pad it a bit.
492 $extra = array("", "" );
495 foreach(file($src) as $l) {
498 if (!strlen($l) || $l[0] == '#') {
502 if (preg_match('#create\s+table\s+([a-z0-9_]+)#i', $l, $m)) {
505 if (preg_match('#create\s+table\s+\`([a-z0-9_]+)\`#i', $l, $m)) {
506 $tbl = 'shop_' . strtolower($m[1]);
507 $l = preg_replace('#create\s+table\s+\`([a-z0-9_]+)\`#i', "CREATE TABLE {$tbl}", $l);
509 if (preg_match('#\`([a-z0-9_]+)\`#i', $l, $m) && !preg_match('#alter\s+table\s+#i', $l)) {
510 $l = preg_replace('#\`([a-z0-9_]+)\`#i', "{$m[1]}_name", $l);
513 if ($tbl && preg_match('#auto_increment#i', $l, $m)) {
514 $l = preg_replace('#auto_increment#i', "default nextval('{$tbl}_seq')", $l);
515 $extra[] = "create sequence {$tbl}_seq;";
519 if (preg_match('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', $l, $m)){
520 $l = preg_replace('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', "ALTER TABLE {$tbl}", $l);
523 // enum value -- use the text instead..
525 if ($tbl && preg_match('#([\w]+)\s+(enum\([\w|\W]+\))#i', $l, $m)) {
526 $l = preg_replace('#enum\([\w|\W]+\)#i', "TEXT", $l);
528 // ignore the alter enum
529 if ($tbl && preg_match('#alter\s+table\s+([\w|\W]+)\s+enum\([\w|\W]+\)#i', $l, $m)) {
533 // UNIQUE KEY .. ignore
534 if ($tbl && preg_match('#UNIQUE KEY#i', $l, $m)) {
535 $last = array_pop($ret);
536 $ret[] = trim($last, ",");
540 if ($tbl && preg_match('#RENAME\s+TO#i', $l, $m)) {
544 if ($tbl && preg_match('#change\s+column#i', $l, $m)) {
548 // INDEX lookup ..ignore
549 if ($tbl && preg_match('#INDEX lookup+([\w|\W]+)#i', $l, $m)) {
550 $last = array_pop($ret);
551 $ret[] = trim($last, ",");
556 // CREATE INDEX ..ignore
557 if (preg_match('#alter\s+table\s+([a-z0-9_]+)\s+add\s+index\s+#i', $l, $m)) {
558 // $l = "CREATE INDEX {$m[1]}_{$m[2]} ON {$m[1]} {$m[3]}";
563 $l = preg_replace('#int\([0-9]+\)#i', 'INT', $l);
565 $l = preg_replace('# datetime#i', ' TIMESTAMP WITHOUT TIME ZONE', $l);
566 $l = preg_replace('# blob#i', ' TEXT', $l);
567 $l = preg_replace('# longtext#i', ' TEXT', $l);
568 $l = preg_replace('# tinyint#i', ' INT', $l);
574 $ret = array_merge($extra,$ret);
575 // echo implode("\n", $ret); exit;
577 file_put_contents($fn, implode("\n", $ret));
583 function checkOpts($opts)
587 foreach($opts as $o=>$v) {
588 if (!preg_match('/^json-/', $o) || empty($v)) {
591 if (!file_exists($v)) {
592 die("File does not exist : OPTION --{$o} = {$v} \n");
596 $modules = array_reverse($this->modulesList());
598 // move 'project' one to the end...
600 foreach ($modules as $module){
601 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
602 if($module == 'Core' || !file_exists($file)){
606 $class = "Pman_{$module}_UpdateDatabase";
608 if(!method_exists($x, 'checkOpts')){
611 $x->checkOpts($opts);
615 static function jsonImportFromArray($opts)
617 foreach($opts as $o=>$v) {
618 if (!preg_match('/^json-/', $o) || empty($v)) {
621 $type = str_replace('_', '-', substr($o,5));
623 $data= json_decode(file_get_contents($v),true);
624 $pg = HTML_FlexyFramework::get()->page;
625 DB_DataObject::factory($type)->importFromArray($pg ,$data,$opts);
635 function runUpdateModulesData()
637 if (class_exists('PDO_DataObjects_Introspection')) {
638 PDO_DataObject_Introspection::$cache = array();
640 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
642 if(!in_array('Core', $this->disabled)){
643 echo "Running jsonImportFromArray\n";
644 Pman_Core_UpdateDatabase::jsonImportFromArray($this->opts);
647 echo "Running updateData on modules\n";
653 $modules = array_reverse($this->modulesList());
655 // move 'project' one to the end...
657 foreach ($modules as $module){
658 if(in_array($module, $this->disabled)){
661 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
662 if($module == 'Core' || !file_exists($file)){
667 $class = "Pman_{$module}_UpdateDatabase";
669 if(!method_exists($x, 'updateData')){
679 function updateDataEnums()
682 $enum = DB_DataObject::Factory('core_enum');
683 //DB_DAtaObject::debugLevel(1);
688 'name' => 'COMPTYPE',
689 'display_name' => 'Company Types',
690 'is_system_enum' => 1,
694 'display_name' => 'Owner',
695 'seqid' => 999, // last...
696 'is_system_enum' => 1,
703 'name' => 'HtmlEditor.font-family',
704 'display_name' => 'HTML Editor font families',
705 'is_system_enum' => 1,
708 'name' => 'Helvetica,Arial,sans-serif',
709 'display_name' => 'Helvetica',
714 'name' => 'Courier New',
715 'display_name' => 'Courier',
720 'display_name' => 'Tahoma',
724 'name' => 'Times New Roman,serif',
725 'display_name' => 'Times',
730 'display_name' => 'Verdana',
742 function updateDataGroups()
745 $groups = DB_DataObject::factory('core_group');
746 $groups->initGroups();
748 $groups->initDatabase($this,array(
750 'name' => 'bcc-email', // group who are bcc'ed on all requests.
751 'type' => 0, // system
754 'name' => 'system-email-from',
755 'type' => 0, // system
758 'name' => 'core-person-signup-bcc',
759 'type' => 0, // system
765 function updateDataCompanies()
768 // fix comptypes enums..
769 $c = DB_DataObject::Factory('core_company');
771 $c->selectAdd('distinct(comptype) as comptype');
772 $c->whereAdd("comptype != ''");
775 foreach($c->fetchAll('comptype') as $cts) {
779 $ctb[]= array( 'etype'=>'COMPTYPE', 'name' => $cts, 'display_name' => ucfirst(strtolower($cts)));
782 $c = DB_DataObject::Factory('core_enum');
785 //DB_DataObject::debugLevel(1);
787 $c = DB_DataObject::Factory('core_company');
789 UPDATE {$c->tableName()}
791 comptype_id = (SELECT id FROM core_enum where etype='comptype' and name={$c->tableName()}.comptype LIMIT 1)
805 function initEmails($templateDir, $emails)
808 $pg = HTML_FlexyFramework::get()->page;
809 foreach($emails as $name=>$data) {
810 $cm = DB_DataObject::factory('core_email');
811 $update = $cm->get('name', $name);
814 if (empty($cm->bcc_group)) {
815 if (empty($data['bcc_group'])) {
816 $this->jerr("missing bcc_group for template $name");
818 $g = DB_DataObject::Factory('core_group')->lookup('name',$data['bcc_group']);
821 $this->jerr("bcc_group {$data['bcc_group']} does not exist when importing template $name");
825 if (!$g->members('email')) {
826 $this->jerr("bcc_group {$data['bcc_group']} does not have any members");
829 $cm->bcc_group = $g->id;
831 if (empty($cm->test_class)) {
832 if (empty($data['test_class'])) {
833 $this->jerr("missing test_class for template $name");
835 $cm->test_class = $data['test_class'];
837 require_once $cm->test_class . '.php';
839 $clsname = str_replace('/','_', $cm->test_class);
841 $method = new ReflectionMethod($clsname , 'test_'. $name) ;
842 $got_it = $method->isStatic();
843 } catch(Exception $e) {
848 $this->jerr("template {$name} does not have a test method {$clsname}::test_{$name}");
852 echo "email: {$name} - checked\n";
853 continue; /// we do not import the body content of templates that exist...
860 // $basedir = $this->bootLoader->rootDir . $mail_template_dir;
864 'file' => $templateDir. $name .'.html'
867 if (!empty($data['master'])) {
868 $opts['master'] = $templateDir . $master .'.html';
870 require_once 'Pman/Core/Import/Core_email.php';
871 $x = new Pman_Core_Import_Core_email();
872 $x->updateOrCreateEmail('', $opts, $cm);
874 echo "email: {$name} - CREATED\n";
879 function updateData()
882 if (class_exists('PDO_DataObjects_Introspection')) {
883 PDO_DataObject_Introspection::$cache = array();
885 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
886 $this->updateDataEnums();
887 $this->updateDataGroups();
888 $this->updateDataCompanies();
890 $c = DB_DataObject::Factory('I18n');
898 function fixMysqlInnodb()
901 static $done_check = false;
905 // innodb in single files is far more efficient that MYD or one big innodb file.
906 // first check if database is using this format.
907 $db = DB_DataObject::factory('core_enum');
908 $db->query("show variables like 'innodb_file_per_table'");
910 if ($db->Value == 'OFF') {
911 die("Error: set innodb_file_per_table = 1 in my.cnf\n\n");
914 $db = DB_DataObject::factory('core_enum');
915 $db->query("select version() as version");
918 if (version_compare($db->version, '5.7', '>=' )) {
920 $db = DB_DataObject::factory('core_enum');
921 $db->query("show variables like 'sql_mode'");
924 $modes = explode(",", $db->Value);
926 // these are 'new' problems with mysql.
928 in_array('NO_ZERO_IN_DATE', $modes) ||
929 in_array('NO_ZERO_DATE', $modes) ||
930 in_array('STRICT_TRANS_TABLES', $modes) ||
931 !in_array('ALLOW_INVALID_DATES', $modes)
933 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");
948 /** ------------- schema fixing ... there is an issue with data imported having the wrong sequence names... --- */
950 function fixSequencesMysql()
955 function fixSequencesPgsql()
959 //DB_DataObject::debugLevel(1);
960 $cs = DB_DataObject::factory('core_enum');
964 CASE WHEN strpos(seq_name, '.') > 0 THEN
967 quote_ident(min(schema_name)) ||'.'|| quote_ident(min(seq_name))
970 ||' OWNED BY '|| quote_ident(min(schema_name)) || '.' ||
971 quote_ident(min(table_name)) ||'.'|| quote_ident(min(column_name)) ||';' as cmd
975 n.nspname AS schema_name,
976 c.relname AS table_name,
977 a.attname AS column_name,
978 regexp_replace(regexp_replace(d.adsrc, E'nextval\\\\(+[''\\\"]*', ''),E'[''\\\"]*::.*\$','') AS seq_name
980 JOIN pg_attribute a ON (c.oid=a.attrelid)
981 JOIN pg_attrdef d ON (a.attrelid=d.adrelid AND a.attnum=d.adnum)
982 JOIN pg_namespace n ON (c.relnamespace=n.oid)
983 WHERE has_schema_privilege(n.oid,'USAGE')
984 AND n.nspname NOT LIKE 'pg!_%' escape '!'
985 AND has_table_privilege(c.oid,'SELECT')
986 AND (NOT a.attisdropped)
987 AND d.adsrc ~ '^nextval'
991 CASE WHEN strpos(seq_name, '.') > 0 THEN
992 substring(seq_name, 1,strpos(seq_name,'.')-1)
997 GROUP BY seq_name HAVING count(*)=1
1000 while ($cs->fetch()) {
1003 foreach($cmds as $cmd) {
1004 $cs = DB_DataObject::factory('core_enum');
1008 $cs = DB_DataObject::factory('core_enum');
1010 SELECT 'SELECT SETVAL(' ||
1011 quote_literal(quote_ident(nspname) || '.' || quote_ident(S.relname)) ||
1012 ', MAX(' || quote_ident(C.attname)|| ')::integer ) FROM ' || nspname || '.' || quote_ident(T.relname)|| ';' as cmd
1018 WHERE S.relkind = 'S'
1020 AND D.refobjid = T.oid
1021 AND D.refobjid = C.attrelid
1022 AND D.refobjsubid = C.attnum
1023 AND NS.oid = T.relnamespace
1027 while ($cs->fetch()) {
1030 foreach($cmds as $cmd) {
1031 $cs = DB_DataObject::factory('core_enum');
1038 var $extensions = array(
1043 function runExtensions()
1046 $ff = HTML_Flexyframework::get();
1048 $dburl = parse_url($ff->database);
1050 $dbtype = $dburl['scheme'];
1052 foreach($this->extensions as $ext) {
1054 $scls = ucfirst($dbtype). $ext;
1055 $cls = __CLASS__ . '_'. $scls;
1056 $fn = implode('/',explode('_', $cls)).'.php';
1057 if (!file_exists(__DIR__.'/UpdateDatabase/'. $scls .'.php')) {
1068 function checkSystem()
1070 // most of these are from File_Convert...
1072 // these are required - and have simple dependancies.
1073 require_once 'System.php';
1079 'rsvg-convert', //librsvg2-bin
1085 // these are prefered - but may have complicated depenacies
1090 'html2text', // not availabe in debian squeeze
1091 'pdftocairo', //poppler-utils - not available in debian squeeze.
1101 foreach($req as $r) {
1102 if (!System::which($r)) {
1108 die("Missing these programs - need installing\n" . implode("\n",$res). "\n");
1110 foreach($pref as $r) {
1111 if (!System::which($r)) {
1117 echo "WARNING: Missing these programs - they may need installing\n". implode("\n",$res);