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.
373 function importmysqldir($dburl, $dir)
376 $this->fixMysqlInnodb(); /// run once
378 echo "Import MYSQL :: $dir\n";
381 require_once 'System.php';
382 $cat = System::which('cat');
383 $mysql = System::which('mysql');
387 $mysql_cmd = $mysql .
388 ' -h ' . $dburl['host'] .
389 ' -u' . escapeshellarg($dburl['user']) .
390 (!empty($dburl['pass']) ? ' -p' . escapeshellarg($dburl['pass']) : '') .
391 ' ' . basename($dburl['path']);
392 //echo $mysql_cmd . "\n" ;
394 $files = glob($dir.'/*.sql');
395 uksort($files, 'strcasecmp');
398 foreach($files as $fn) {
401 if (preg_match('/migrate/i', basename($fn))) { // skip migration scripts at present..
404 // .my.sql but not .pg.sql
405 if (preg_match('#\.[a-z]{2}\.sql#i', basename($fn))
406 && !preg_match('#\.my\.sql#i', basename($fn))
407 ) { // skip migration scripts at present..
410 if (!strlen(trim($fn))) {
414 $cmd = "$mysql_cmd -f < " . escapeshellarg($fn) ." 2>&1" ;
416 echo basename($dir).'/'. basename($fn) . '::' . $cmd. ($this->cli ? "\n" : "<BR>\n");
419 $fp = popen($cmd, "r");
422 // send the current file part to the browser
423 $line = trim(fgets($fp, 1024));
428 if (!preg_match('/^ERROR\s+([0-9]+)/', $line, $matches)) {
429 echo " ---- {$line}\n"; flush();
433 switch($matches[1]) {
434 case 1017: // cause by renaming table -- old one does not exist..
435 case 1050: // create tables triggers this..
436 case 1060: // Duplicate column name
437 case 1061: // Duplicate key name - triggered by add index.. but could hide error. - unlikely though.
438 case 1091: // drop index -- name does not exist.. might hide errors..
440 case 1146: // drop a index on an unknown table.. - happens rarely...
441 case 1054: // Unknown column -- triggered by CHANGE COLUMN - but may hide other errrors..
447 echo " ---- {$line}\n"; flush();
451 // 1051: // Unknown table -- normally drop = add iff exists..
452 echo "File: $fn\n$line\n";
468 * simple regex based convert mysql to pgsql...
470 function convertToPG($src)
472 //echo "Convert $src\n";
474 $fn = $this->tempName('sql');
476 $ret = array( ); // pad it a bit.
477 $extra = array("", "" );
480 foreach(file($src) as $l) {
483 if (!strlen($l) || $l[0] == '#') {
487 if (preg_match('#create\s+table\s+([a-z0-9_]+)#i', $l, $m)) {
490 if (preg_match('#create\s+table\s+\`([a-z0-9_]+)\`#i', $l, $m)) {
491 $tbl = 'shop_' . strtolower($m[1]);
492 $l = preg_replace('#create\s+table\s+\`([a-z0-9_]+)\`#i', "CREATE TABLE {$tbl}", $l);
494 if (preg_match('#\`([a-z0-9_]+)\`#i', $l, $m) && !preg_match('#alter\s+table\s+#i', $l)) {
495 $l = preg_replace('#\`([a-z0-9_]+)\`#i', "{$m[1]}_name", $l);
498 if ($tbl && preg_match('#auto_increment#i', $l, $m)) {
499 $l = preg_replace('#auto_increment#i', "default nextval('{$tbl}_seq')", $l);
500 $extra[] = "create sequence {$tbl}_seq;";
504 if (preg_match('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', $l, $m)){
505 $l = preg_replace('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', "ALTER TABLE {$tbl}", $l);
508 // enum value -- use the text instead..
510 if ($tbl && preg_match('#([\w]+)\s+(enum\([\w|\W]+\))#i', $l, $m)) {
511 $l = preg_replace('#enum\([\w|\W]+\)#i', "TEXT", $l);
513 // ignore the alter enum
514 if ($tbl && preg_match('#alter\s+table\s+([\w|\W]+)\s+enum\([\w|\W]+\)#i', $l, $m)) {
518 // UNIQUE KEY .. ignore
519 if ($tbl && preg_match('#UNIQUE KEY#i', $l, $m)) {
520 $last = array_pop($ret);
521 $ret[] = trim($last, ",");
525 if ($tbl && preg_match('#RENAME\s+TO#i', $l, $m)) {
529 if ($tbl && preg_match('#change\s+column#i', $l, $m)) {
533 // INDEX lookup ..ignore
534 if ($tbl && preg_match('#INDEX lookup+([\w|\W]+)#i', $l, $m)) {
535 $last = array_pop($ret);
536 $ret[] = trim($last, ",");
541 // CREATE INDEX ..ignore
542 if (preg_match('#alter\s+table\s+([a-z0-9_]+)\s+add\s+index\s+#i', $l, $m)) {
543 // $l = "CREATE INDEX {$m[1]}_{$m[2]} ON {$m[1]} {$m[3]}";
548 $l = preg_replace('#int\([0-9]+\)#i', 'INT', $l);
550 $l = preg_replace('# datetime#i', ' TIMESTAMP WITHOUT TIME ZONE', $l);
551 $l = preg_replace('# blob#i', ' TEXT', $l);
552 $l = preg_replace('# longtext#i', ' TEXT', $l);
553 $l = preg_replace('# tinyint#i', ' INT', $l);
559 $ret = array_merge($extra,$ret);
560 // echo implode("\n", $ret); exit;
562 file_put_contents($fn, implode("\n", $ret));
568 function checkOpts($opts)
572 foreach($opts as $o=>$v) {
573 if (!preg_match('/^json-/', $o) || empty($v)) {
576 if (!file_exists($v)) {
577 die("File does not exist : OPTION --{$o} = {$v} \n");
581 $modules = array_reverse($this->modulesList());
583 // move 'project' one to the end...
585 foreach ($modules as $module){
586 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
587 if($module == 'Core' || !file_exists($file)){
591 $class = "Pman_{$module}_UpdateDatabase";
593 if(!method_exists($x, 'checkOpts')){
596 $x->checkOpts($opts);
600 static function jsonImportFromArray($opts)
602 foreach($opts as $o=>$v) {
603 if (!preg_match('/^json-/', $o) || empty($v)) {
606 $type = str_replace('_', '-', substr($o,5));
608 $data= json_decode(file_get_contents($v),true);
609 $pg = HTML_FlexyFramework::get()->page;
610 DB_DataObject::factory($type)->importFromArray($pg ,$data,$opts);
620 function runUpdateModulesData()
622 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
624 if(!in_array('Core', $this->disabled)){
625 echo "Running jsonImportFromArray\n";
626 Pman_Core_UpdateDatabase::jsonImportFromArray($this->opts);
629 echo "Running updateData on modules\n";
635 $modules = array_reverse($this->modulesList());
637 // move 'project' one to the end...
639 foreach ($modules as $module){
640 if(in_array($module, $this->disabled)){
643 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
644 if($module == 'Core' || !file_exists($file)){
649 $class = "Pman_{$module}_UpdateDatabase";
651 if(!method_exists($x, 'updateData')){
661 function updateDataEnums()
664 $enum = DB_DataObject::Factory('core_enum');
665 //DB_DAtaObject::debugLevel(1);
670 'name' => 'COMPTYPE',
671 'display_name' => 'Company Types',
672 'is_system_enum' => 1,
676 'display_name' => 'Owner',
677 'seqid' => 999, // last...
678 'is_system_enum' => 1,
685 'name' => 'HtmlEditor.font-family',
686 'display_name' => 'HTML Editor font families',
687 'is_system_enum' => 1,
690 'name' => 'Helvetica,Arial,sans-serif',
691 'display_name' => 'Helvetica',
696 'name' => 'Courier New',
697 'display_name' => 'Courier',
702 'display_name' => 'Tahoma',
706 'name' => 'Times New Roman,serif',
707 'display_name' => 'Times',
712 'display_name' => 'Verdana',
724 function updateDataGroups()
727 $groups = DB_DataObject::factory('core_group');
728 $groups->initGroups();
730 $groups->initDatabase($this,array(
732 'name' => 'bcc-email', // group who are bcc'ed on all requests.
733 'type' => 0, // system
736 'name' => 'system-email-from',
737 'type' => 0, // system
740 'name' => 'core-person-signup-bcc',
741 'type' => 0, // system
747 function updateDataCompanies()
750 // fix comptypes enums..
751 $c = DB_DataObject::Factory('core_company');
753 $c->selectAdd('distinct(comptype) as comptype');
754 $c->whereAdd("comptype != ''");
757 foreach($c->fetchAll('comptype') as $cts) {
761 $ctb[]= array( 'etype'=>'COMPTYPE', 'name' => $cts, 'display_name' => ucfirst(strtolower($cts)));
764 $c = DB_DataObject::Factory('core_enum');
767 //DB_DataObject::debugLevel(1);
769 $c = DB_DataObject::Factory('core_company');
771 UPDATE {$c->tableName()}
773 comptype_id = (SELECT id FROM core_enum where etype='comptype' and name={$c->tableName()}.comptype LIMIT 1)
787 function initEmails($templateDir, $emails)
790 $pg = HTML_FlexyFramework::get()->page;
791 foreach($emails as $name=>$data) {
792 $cm = DB_DataObject::factory('core_email');
793 $update = $cm->get('name', $name);
796 if (empty($cm->bcc_group)) {
797 if (empty($data['bcc_group'])) {
798 $this->jerr("missing bcc_group for template $name");
800 $g = DB_DataObject::Factory('core_group')->lookup('name',$data['bcc_group']);
803 $this->jerr("bcc_group {$data['bcc_group']} does not exist when importing template $name");
807 if (!$g->members('email')) {
808 $this->jerr("bcc_group {$data['bcc_group']} does not have any members");
811 $cm->bcc_group = $g->id;
813 if (empty($cm->test_class)) {
814 if (empty($data['test_class'])) {
815 $this->jerr("missing test_class for template $name");
817 $cm->test_class = $data['test_class'];
819 require_once $cm->test_class . '.php';
821 $clsname = str_replace('/','_', $cm->test_class);
823 $method = new ReflectionMethod($clsname , 'test_'. $name) ;
824 $got_it = $method->isStatic();
825 } catch(Exception $e) {
830 $this->jerr("template {$name} does not have a test method {$clsname}::test_{$name}");
834 echo "email: {$name} - checked\n";
835 continue; /// we do not import the body content of templates that exist...
842 // $basedir = $this->bootLoader->rootDir . $mail_template_dir;
846 'file' => $templateDir. $name .'.html'
849 if (!empty($data['master'])) {
850 $opts['master'] = $templateDir . $master .'.html';
852 require_once 'Pman/Core/Import/Core_email.php';
853 $x = new Pman_Core_Import_Core_email();
854 $x->updateOrCreateEmail('', $opts, $cm);
856 echo "email: {$name} - CREATED\n";
861 function updateData()
864 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
865 $this->updateDataEnums();
866 $this->updateDataGroups();
867 $this->updateDataCompanies();
869 $c = DB_DataObject::Factory('I18n');
877 function fixMysqlInnodb()
880 static $done_check = false;
884 // innodb in single files is far more efficient that MYD or one big innodb file.
885 // first check if database is using this format.
886 $db = DB_DataObject::factory('core_enum');
887 $db->query("show variables like 'innodb_file_per_table'");
889 if ($db->Value == 'OFF') {
890 die("Error: set innodb_file_per_table = 1 in my.cnf\n\n");
893 $db = DB_DataObject::factory('core_enum');
894 $db->query("select version() as version");
897 if (version_compare($db->version, '5.7', '>=' )) {
899 $db = DB_DataObject::factory('core_enum');
900 $db->query("show variables like 'sql_mode'");
903 $modes = explode(",", $db->Value);
905 // these are 'new' problems with mysql.
907 in_array('NO_ZERO_IN_DATE', $modes) ||
908 in_array('NO_ZERO_DATE', $modes) ||
909 in_array('STRICT_TRANS_TABLES', $modes) ||
910 !in_array('ALLOW_INVALID_DATES', $modes)
912 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");
927 /** ------------- schema fixing ... there is an issue with data imported having the wrong sequence names... --- */
929 function fixSequencesMysql()
934 function fixSequencesPgsql()
938 //DB_DataObject::debugLevel(1);
939 $cs = DB_DataObject::factory('core_enum');
943 CASE WHEN strpos(seq_name, '.') > 0 THEN
946 quote_ident(min(schema_name)) ||'.'|| quote_ident(min(seq_name))
949 ||' OWNED BY '|| quote_ident(min(schema_name)) || '.' ||
950 quote_ident(min(table_name)) ||'.'|| quote_ident(min(column_name)) ||';' as cmd
954 n.nspname AS schema_name,
955 c.relname AS table_name,
956 a.attname AS column_name,
957 regexp_replace(regexp_replace(d.adsrc, E'nextval\\\\(+[''\\\"]*', ''),E'[''\\\"]*::.*\$','') AS seq_name
959 JOIN pg_attribute a ON (c.oid=a.attrelid)
960 JOIN pg_attrdef d ON (a.attrelid=d.adrelid AND a.attnum=d.adnum)
961 JOIN pg_namespace n ON (c.relnamespace=n.oid)
962 WHERE has_schema_privilege(n.oid,'USAGE')
963 AND n.nspname NOT LIKE 'pg!_%' escape '!'
964 AND has_table_privilege(c.oid,'SELECT')
965 AND (NOT a.attisdropped)
966 AND d.adsrc ~ '^nextval'
970 CASE WHEN strpos(seq_name, '.') > 0 THEN
971 substring(seq_name, 1,strpos(seq_name,'.')-1)
976 GROUP BY seq_name HAVING count(*)=1
979 while ($cs->fetch()) {
982 foreach($cmds as $cmd) {
983 $cs = DB_DataObject::factory('core_enum');
987 $cs = DB_DataObject::factory('core_enum');
989 SELECT 'SELECT SETVAL(' ||
990 quote_literal(quote_ident(nspname) || '.' || quote_ident(S.relname)) ||
991 ', MAX(' || quote_ident(C.attname)|| ')::integer ) FROM ' || nspname || '.' || quote_ident(T.relname)|| ';' as cmd
997 WHERE S.relkind = 'S'
999 AND D.refobjid = T.oid
1000 AND D.refobjid = C.attrelid
1001 AND D.refobjsubid = C.attnum
1002 AND NS.oid = T.relnamespace
1006 while ($cs->fetch()) {
1009 foreach($cmds as $cmd) {
1010 $cs = DB_DataObject::factory('core_enum');
1017 var $extensions = array(
1022 function runExtensions()
1025 $ff = HTML_Flexyframework::get();
1027 $dburl = parse_url($ff->DB_DataObject['database']);
1029 $dbtype = $dburl['scheme'];
1031 foreach($this->extensions as $ext) {
1033 $scls = ucfirst($dbtype). $ext;
1034 $cls = __CLASS__ . '_'. $scls;
1035 $fn = implode('/',explode('_', $cls)).'.php';
1036 if (!file_exists(__DIR__.'/UpdateDatabase/'. $scls .'.php')) {
1047 function checkSystem()
1049 // most of these are from File_Convert...
1051 // these are required - and have simple dependancies.
1052 require_once 'System.php';
1058 'rsvg-convert', //librsvg2-bin
1064 // these are prefered - but may have complicated depenacies
1069 'html2text', // not availabe in debian squeeze
1070 'pdftocairo', //poppler-utils - not available in debian squeeze.
1080 foreach($req as $r) {
1081 if (!System::which($r)) {
1087 $this->jerr("Missing these programs - need installing\n" . implode("\n",$res));
1089 foreach($pref as $r) {
1090 if (!System::which($r)) {
1096 echo "WARNING: Missing these programs - they may need installing\n". implode("\n",$res);