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();
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'];
207 $dirmethod = 'import' . $dburl['scheme'] . 'dir';
212 $ar = $this->modulesList();
217 if(in_array($m, $this->disabled)){
218 echo "module $m is disabled \n";
222 echo "Importing SQL from module $m\n";
223 if (!empty($this->opts['only-module-sql']) && $m != $this->opts['only-module-sql']) {
228 // check to see if the class has
232 $file = $this->rootDir. "/Pman/$m/UpdateDatabase.php";
233 if($m != 'Core' && file_exists($file)){
236 $class = "Pman_{$m}_UpdateDatabase";
238 if(method_exists($x, 'importModuleSQL')){
239 echo "Importing SQL from module $m using Module::importModuleSQL\n";
240 $x->opts = $this->opts;
241 $x->rootDir = $this->rootDir;
242 $x->importModuleSQL($dburl);
247 echo "Importing SQL from module $m\n";
250 // if init has been called
252 if (!empty($this->opts['init'])) {
253 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}.init");
259 $fd = $this->rootDir. "/Pman/$m/DataObjects";
261 $this->{$dirmethod}($dburl, $fd);
264 // new -- sql directory..
265 // new style will not support migrate ... they have to go into mysql-migrate.... directories..
266 // new style will not support pg.sql etc.. naming - that's what the direcotries are for..
268 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/sql");
269 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}");
273 if (!empty($this->opts['init']) && file_exists($this->rootDir. "/Pman/$m/{$dbtype}.initdata")) {
274 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
276 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}.initdata");
277 $this->{'fixSequences'. $dbtype}();
289 /** -------------- code to handle importing a whole directory of files into the database ------- **/
292 function importpgsqldir($url, $dir, $disable_triggers = false)
294 $ff = HTML_FlexyFramework::get();
296 require_once 'System.php';
297 $cat = System::which('cat');
298 $psql = System::which('psql');
301 if (!empty($url['pass'])) {
302 putenv("PGPASSWORD=". $url['pass']);
306 ' -h ' . $url['host'] .
307 ' -U' . escapeshellarg($url['user']) .
308 ' ' . basename($url['path']);
311 echo $psql_cmd . "\n" ;
312 echo "scan : $dir\n";
315 $files = array($dir);
320 $files = glob($dir.'/*.sql');
321 uksort($files, 'strcasecmp');
323 //$lsort = create_function('$a,$b','return strlen($a) > strlen($b) ? 1 : -1;');
324 //usort($files, $lsort);
327 foreach($files as $bfn) {
330 if (preg_match('/migrate/i', basename($bfn))) { // skip migration scripts at present..
333 if (preg_match('#\.[a-z]{2}\.sql#i', basename($bfn))
334 && !preg_match('#\.pg\.sql#i', basename($bfn))
335 ) { // skip migration scripts at present..
340 if (!preg_match('/pgsql/', basename($dir) )) {
341 if ( !preg_match('#\.pg\.sql$#', basename($bfn))) {
342 $fn = $this->convertToPG($bfn);
346 // files ending in .pg.sql are native postgres files.. ## depricated
349 $cmd = "$psql_cmd < " . escapeshellarg($fn ? $fn : $bfn) . ' 2>&1' ;
351 echo "$bfn: $cmd ". ($ff->cli ? "\n" : "<BR>\n");
367 * mysql - does not support conversions.
371 function importmysqldiri($dburl, $dir) {
372 return $this->importmysqldir($dburl, $dir);
375 function importmysqldir($dburl, $dir)
378 $this->fixMysqlInnodb(); /// run once
380 echo "Import MYSQL :: $dir\n";
383 require_once 'System.php';
384 $cat = System::which('cat');
385 $mysql = System::which('mysql');
389 $mysql_cmd = $mysql .
390 ' -h ' . $dburl['host'] .
391 ' -u' . escapeshellarg($dburl['user']) .
392 (!empty($dburl['pass']) ? ' -p' . escapeshellarg($dburl['pass']) : '') .
393 ' ' . basename($dburl['path']);
394 //echo $mysql_cmd . "\n" ;
396 $files = glob($dir.'/*.sql');
397 uksort($files, 'strcasecmp');
400 foreach($files as $fn) {
403 if (preg_match('/migrate/i', basename($fn))) { // skip migration scripts at present..
406 // .my.sql but not .pg.sql
407 if (preg_match('#\.[a-z]{2}\.sql#i', basename($fn))
408 && !preg_match('#\.my\.sql#i', basename($fn))
409 ) { // skip migration scripts at present..
412 if (!strlen(trim($fn))) {
416 $cmd = "$mysql_cmd -f < " . escapeshellarg($fn) ." 2>&1" ;
418 echo basename($dir).'/'. basename($fn) . '::' . $cmd. ($this->cli ? "\n" : "<BR>\n");
421 $fp = popen($cmd, "r");
424 // send the current file part to the browser
425 $line = trim(fgets($fp, 1024));
430 if (!preg_match('/^ERROR\s+([0-9]+)/', $line, $matches)) {
431 echo " ---- {$line}\n"; flush();
435 switch($matches[1]) {
436 case 1017: // cause by renaming table -- old one does not exist..
437 case 1050: // create tables triggers this..
438 case 1060: // Duplicate column name
439 case 1061: // Duplicate key name - triggered by add index.. but could hide error. - unlikely though.
440 case 1091: // drop index -- name does not exist.. might hide errors..
442 case 1146: // drop a index on an unknown table.. - happens rarely...
443 case 1054: // Unknown column -- triggered by CHANGE COLUMN - but may hide other errrors..
449 echo " ---- {$line}\n"; flush();
453 // 1051: // Unknown table -- normally drop = add iff exists..
454 echo "File: $fn\n$line\n";
470 * simple regex based convert mysql to pgsql...
472 function convertToPG($src)
474 //echo "Convert $src\n";
476 $fn = $this->tempName('sql');
478 $ret = array( ); // pad it a bit.
479 $extra = array("", "" );
482 foreach(file($src) as $l) {
485 if (!strlen($l) || $l[0] == '#') {
489 if (preg_match('#create\s+table\s+([a-z0-9_]+)#i', $l, $m)) {
492 if (preg_match('#create\s+table\s+\`([a-z0-9_]+)\`#i', $l, $m)) {
493 $tbl = 'shop_' . strtolower($m[1]);
494 $l = preg_replace('#create\s+table\s+\`([a-z0-9_]+)\`#i', "CREATE TABLE {$tbl}", $l);
496 if (preg_match('#\`([a-z0-9_]+)\`#i', $l, $m) && !preg_match('#alter\s+table\s+#i', $l)) {
497 $l = preg_replace('#\`([a-z0-9_]+)\`#i', "{$m[1]}_name", $l);
500 if ($tbl && preg_match('#auto_increment#i', $l, $m)) {
501 $l = preg_replace('#auto_increment#i', "default nextval('{$tbl}_seq')", $l);
502 $extra[] = "create sequence {$tbl}_seq;";
506 if (preg_match('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', $l, $m)){
507 $l = preg_replace('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', "ALTER TABLE {$tbl}", $l);
510 // enum value -- use the text instead..
512 if ($tbl && preg_match('#([\w]+)\s+(enum\([\w|\W]+\))#i', $l, $m)) {
513 $l = preg_replace('#enum\([\w|\W]+\)#i', "TEXT", $l);
515 // ignore the alter enum
516 if ($tbl && preg_match('#alter\s+table\s+([\w|\W]+)\s+enum\([\w|\W]+\)#i', $l, $m)) {
520 // UNIQUE KEY .. ignore
521 if ($tbl && preg_match('#UNIQUE KEY#i', $l, $m)) {
522 $last = array_pop($ret);
523 $ret[] = trim($last, ",");
527 if ($tbl && preg_match('#RENAME\s+TO#i', $l, $m)) {
531 if ($tbl && preg_match('#change\s+column#i', $l, $m)) {
535 // INDEX lookup ..ignore
536 if ($tbl && preg_match('#INDEX lookup+([\w|\W]+)#i', $l, $m)) {
537 $last = array_pop($ret);
538 $ret[] = trim($last, ",");
543 // CREATE INDEX ..ignore
544 if (preg_match('#alter\s+table\s+([a-z0-9_]+)\s+add\s+index\s+#i', $l, $m)) {
545 // $l = "CREATE INDEX {$m[1]}_{$m[2]} ON {$m[1]} {$m[3]}";
550 $l = preg_replace('#int\([0-9]+\)#i', 'INT', $l);
552 $l = preg_replace('# datetime#i', ' TIMESTAMP WITHOUT TIME ZONE', $l);
553 $l = preg_replace('# blob#i', ' TEXT', $l);
554 $l = preg_replace('# longtext#i', ' TEXT', $l);
555 $l = preg_replace('# tinyint#i', ' INT', $l);
561 $ret = array_merge($extra,$ret);
562 // echo implode("\n", $ret); exit;
564 file_put_contents($fn, implode("\n", $ret));
570 function checkOpts($opts)
574 foreach($opts as $o=>$v) {
575 if (!preg_match('/^json-/', $o) || empty($v)) {
578 if (!file_exists($v)) {
579 die("File does not exist : OPTION --{$o} = {$v} \n");
583 $modules = array_reverse($this->modulesList());
585 // move 'project' one to the end...
587 foreach ($modules as $module){
588 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
589 if($module == 'Core' || !file_exists($file)){
593 $class = "Pman_{$module}_UpdateDatabase";
595 if(!method_exists($x, 'checkOpts')){
598 $x->checkOpts($opts);
602 static function jsonImportFromArray($opts)
604 foreach($opts as $o=>$v) {
605 if (!preg_match('/^json-/', $o) || empty($v)) {
608 $type = str_replace('_', '-', substr($o,5));
610 $data= json_decode(file_get_contents($v),true);
611 $pg = HTML_FlexyFramework::get()->page;
612 DB_DataObject::factory($type)->importFromArray($pg ,$data,$opts);
622 function runUpdateModulesData()
624 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
626 if(!in_array('Core', $this->disabled)){
627 echo "Running jsonImportFromArray\n";
628 Pman_Core_UpdateDatabase::jsonImportFromArray($this->opts);
631 echo "Running updateData on modules\n";
637 $modules = array_reverse($this->modulesList());
639 // move 'project' one to the end...
641 foreach ($modules as $module){
642 if(in_array($module, $this->disabled)){
645 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
646 if($module == 'Core' || !file_exists($file)){
651 $class = "Pman_{$module}_UpdateDatabase";
653 if(!method_exists($x, 'updateData')){
663 function updateDataEnums()
666 $enum = DB_DataObject::Factory('core_enum');
667 //DB_DAtaObject::debugLevel(1);
672 'name' => 'COMPTYPE',
673 'display_name' => 'Company Types',
674 'is_system_enum' => 1,
678 'display_name' => 'Owner',
679 'seqid' => 999, // last...
680 'is_system_enum' => 1,
687 'name' => 'HtmlEditor.font-family',
688 'display_name' => 'HTML Editor font families',
689 'is_system_enum' => 1,
692 'name' => 'Helvetica,Arial,sans-serif',
693 'display_name' => 'Helvetica',
698 'name' => 'Courier New',
699 'display_name' => 'Courier',
704 'display_name' => 'Tahoma',
708 'name' => 'Times New Roman,serif',
709 'display_name' => 'Times',
714 'display_name' => 'Verdana',
726 function updateDataGroups()
729 $groups = DB_DataObject::factory('core_group');
730 $groups->initGroups();
732 $groups->initDatabase($this,array(
734 'name' => 'bcc-email', // group who are bcc'ed on all requests.
735 'type' => 0, // system
738 'name' => 'system-email-from',
739 'type' => 0, // system
742 'name' => 'core-person-signup-bcc',
743 'type' => 0, // system
749 function updateDataCompanies()
752 // fix comptypes enums..
753 $c = DB_DataObject::Factory('core_company');
755 $c->selectAdd('distinct(comptype) as comptype');
756 $c->whereAdd("comptype != ''");
759 foreach($c->fetchAll('comptype') as $cts) {
763 $ctb[]= array( 'etype'=>'COMPTYPE', 'name' => $cts, 'display_name' => ucfirst(strtolower($cts)));
766 $c = DB_DataObject::Factory('core_enum');
769 //DB_DataObject::debugLevel(1);
771 $c = DB_DataObject::Factory('core_company');
773 UPDATE {$c->tableName()}
775 comptype_id = (SELECT id FROM core_enum where etype='comptype' and name={$c->tableName()}.comptype LIMIT 1)
789 function initEmails($templateDir, $emails)
792 $pg = HTML_FlexyFramework::get()->page;
793 foreach($emails as $name=>$data) {
794 $cm = DB_DataObject::factory('core_email');
795 $update = $cm->get('name', $name);
798 if (empty($cm->bcc_group)) {
799 if (empty($data['bcc_group'])) {
800 $this->jerr("missing bcc_group for template $name");
802 $g = DB_DataObject::Factory('core_group')->lookup('name',$data['bcc_group']);
805 $this->jerr("bcc_group {$data['bcc_group']} does not exist when importing template $name");
809 if (!$g->members('email')) {
810 $this->jerr("bcc_group {$data['bcc_group']} does not have any members");
813 $cm->bcc_group = $g->id;
815 if (empty($cm->test_class)) {
816 if (empty($data['test_class'])) {
817 $this->jerr("missing test_class for template $name");
819 $cm->test_class = $data['test_class'];
821 require_once $cm->test_class . '.php';
823 $clsname = str_replace('/','_', $cm->test_class);
825 $method = new ReflectionMethod($clsname , 'test_'. $name) ;
826 $got_it = $method->isStatic();
827 } catch(Exception $e) {
832 $this->jerr("template {$name} does not have a test method {$clsname}::test_{$name}");
836 echo "email: {$name} - checked\n";
837 continue; /// we do not import the body content of templates that exist...
844 // $basedir = $this->bootLoader->rootDir . $mail_template_dir;
848 'file' => $templateDir. $name .'.html'
851 if (!empty($data['master'])) {
852 $opts['master'] = $templateDir . $master .'.html';
854 require_once 'Pman/Core/Import/Core_email.php';
855 $x = new Pman_Core_Import_Core_email();
856 $x->updateOrCreateEmail('', $opts, $cm);
858 echo "email: {$name} - CREATED\n";
863 function updateData()
866 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
867 $this->updateDataEnums();
868 $this->updateDataGroups();
869 $this->updateDataCompanies();
871 $c = DB_DataObject::Factory('I18n');
879 function fixMysqlInnodb()
882 static $done_check = false;
886 // innodb in single files is far more efficient that MYD or one big innodb file.
887 // first check if database is using this format.
888 $db = DB_DataObject::factory('core_enum');
889 $db->query("show variables like 'innodb_file_per_table'");
891 if ($db->Value == 'OFF') {
892 die("Error: set innodb_file_per_table = 1 in my.cnf\n\n");
895 $db = DB_DataObject::factory('core_enum');
896 $db->query("select version() as version");
899 if (version_compare($db->version, '5.7', '>=' )) {
901 $db = DB_DataObject::factory('core_enum');
902 $db->query("show variables like 'sql_mode'");
905 $modes = explode(",", $db->Value);
907 // these are 'new' problems with mysql.
909 in_array('NO_ZERO_IN_DATE', $modes) ||
910 in_array('NO_ZERO_DATE', $modes) ||
911 in_array('STRICT_TRANS_TABLES', $modes) ||
912 !in_array('ALLOW_INVALID_DATES', $modes)
914 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");
929 /** ------------- schema fixing ... there is an issue with data imported having the wrong sequence names... --- */
931 function fixSequencesMysql()
936 function fixSequencesPgsql()
940 //DB_DataObject::debugLevel(1);
941 $cs = DB_DataObject::factory('core_enum');
945 CASE WHEN strpos(seq_name, '.') > 0 THEN
948 quote_ident(min(schema_name)) ||'.'|| quote_ident(min(seq_name))
951 ||' OWNED BY '|| quote_ident(min(schema_name)) || '.' ||
952 quote_ident(min(table_name)) ||'.'|| quote_ident(min(column_name)) ||';' as cmd
956 n.nspname AS schema_name,
957 c.relname AS table_name,
958 a.attname AS column_name,
959 regexp_replace(regexp_replace(d.adsrc, E'nextval\\\\(+[''\\\"]*', ''),E'[''\\\"]*::.*\$','') AS seq_name
961 JOIN pg_attribute a ON (c.oid=a.attrelid)
962 JOIN pg_attrdef d ON (a.attrelid=d.adrelid AND a.attnum=d.adnum)
963 JOIN pg_namespace n ON (c.relnamespace=n.oid)
964 WHERE has_schema_privilege(n.oid,'USAGE')
965 AND n.nspname NOT LIKE 'pg!_%' escape '!'
966 AND has_table_privilege(c.oid,'SELECT')
967 AND (NOT a.attisdropped)
968 AND d.adsrc ~ '^nextval'
972 CASE WHEN strpos(seq_name, '.') > 0 THEN
973 substring(seq_name, 1,strpos(seq_name,'.')-1)
978 GROUP BY seq_name HAVING count(*)=1
981 while ($cs->fetch()) {
984 foreach($cmds as $cmd) {
985 $cs = DB_DataObject::factory('core_enum');
989 $cs = DB_DataObject::factory('core_enum');
991 SELECT 'SELECT SETVAL(' ||
992 quote_literal(quote_ident(nspname) || '.' || quote_ident(S.relname)) ||
993 ', MAX(' || quote_ident(C.attname)|| ')::integer ) FROM ' || nspname || '.' || quote_ident(T.relname)|| ';' as cmd
999 WHERE S.relkind = 'S'
1001 AND D.refobjid = T.oid
1002 AND D.refobjid = C.attrelid
1003 AND D.refobjsubid = C.attnum
1004 AND NS.oid = T.relnamespace
1008 while ($cs->fetch()) {
1011 foreach($cmds as $cmd) {
1012 $cs = DB_DataObject::factory('core_enum');
1019 var $extensions = array(
1024 function runExtensions()
1027 $ff = HTML_Flexyframework::get();
1029 $dburl = parse_url($ff->DB_DataObject['database']);
1031 $dbtype = $dburl['scheme'];
1033 foreach($this->extensions as $ext) {
1035 $scls = ucfirst($dbtype). $ext;
1036 $cls = __CLASS__ . '_'. $scls;
1037 $fn = implode('/',explode('_', $cls)).'.php';
1038 if (!file_exists(__DIR__.'/UpdateDatabase/'. $scls .'.php')) {
1049 function checkSystem()
1051 // most of these are from File_Convert...
1053 // these are required - and have simple dependancies.
1054 require_once 'System.php';
1060 'rsvg-convert', //librsvg2-bin
1066 // these are prefered - but may have complicated depenacies
1071 'html2text', // not availabe in debian squeeze
1072 'pdftocairo', //poppler-utils - not available in debian squeeze.
1082 foreach($req as $r) {
1083 if (!System::which($r)) {
1089 $this->jerr("Missing these programs - need installing\n" . implode("\n",$res));
1091 foreach($pref as $r) {
1092 if (!System::which($r)) {
1098 echo "WARNING: Missing these programs - they may need installing\n". implode("\n",$res);