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();
112 var $local_base_url = false;
117 $ff = HTML_FlexyFramework::get();
118 if (!empty($ff->cli)) {
123 parent::getAuth(); // load company!
124 $au = $this->getAuthUser();
125 if (!$au || $au->company()->comptype != 'OWNER') {
126 $this->jerr("Not authenticated", array('authFailure' => true));
128 $this->authUser = $au;
132 function get($args, $opts=array())
134 PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, array($this, 'onPearError'));
136 $this->checkSystem();
138 if (class_exists('PDO_DataObjects_Introspection')) {
139 PDO_DataObject_Introspection::$cache = array();
142 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
144 $ff = HTML_FlexyFramework::get();
146 if(!isset($ff->Pman) || !isset($ff->Pman['local_base_url'])){
147 die("Please setup local_base_url");
150 $this->local_base_url = $ff->Pman['local_base_url'];
152 if(!empty($ff->Core_Notify)){
153 // require_once 'Pman/Core/NotifySmtpCheck.php';
154 // $x = new Pman_Core_NotifySmtpCheck();
158 $this->disabled = explode(',', $ff->disable);
160 //$this->fixSequencesPgsql();exit;
163 // ask all the modules to verify the opts
165 $this->checkOpts($opts);
168 // do this first, so the innodb change + utf8 fixes column max sizes
170 // this will trigger errors about freetext indexes - we will have to remove them manually.?
171 // 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..)
173 $this->runExtensions();
176 if (empty($opts['data-only'])) {
179 if (!empty($opts['only-module-sql'])) {
183 $this->runUpdateModulesData();
186 if (!empty($opts['add-company']) && !in_array('Core', $this->disabled)) {
187 // make sure we have a good cache...?
189 DB_DataObject::factory('core_company')->initCompanies($this, $opts);
192 $this->runExtensions();
200 * imports SQL files from all DataObjects directories....
202 * except any matching /migrate/
207 // loop through all the modules, and see if they have a importSQL method?
210 $ff = HTML_Flexyframework::get();
212 $dburl = parse_url($ff->database); // used to be DB_DataObject['database'] - but not portable to PDO
214 //$this->{'import' . $url['scheme']}($url);
216 $dbtype = $dburl['scheme'];
219 $dirmethod = 'import' . $dburl['scheme'] . 'dir';
224 $ar = $this->modulesList();
229 if(in_array($m, $this->disabled)){
230 echo "module $m is disabled \n";
234 echo "Importing SQL from module $m\n";
235 if (!empty($this->opts['only-module-sql']) && $m != $this->opts['only-module-sql']) {
240 // check to see if the class has
244 $file = $this->rootDir. "/Pman/$m/UpdateDatabase.php";
245 if($m != 'Core' && file_exists($file)){
248 $class = "Pman_{$m}_UpdateDatabase";
250 if(method_exists($x, 'importModuleSQL')){
251 echo "Importing SQL from module $m using Module::importModuleSQL\n";
252 $x->opts = $this->opts;
253 $x->rootDir = $this->rootDir;
254 $x->importModuleSQL($dburl);
259 echo "Importing SQL from module $m\n";
262 // if init has been called
264 if (!empty($this->opts['init'])) {
265 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}.init");
271 $fd = $this->rootDir. "/Pman/$m/DataObjects";
273 $this->{$dirmethod}($dburl, $fd);
276 // new -- sql directory..
277 // new style will not support migrate ... they have to go into mysql-migrate.... directories..
278 // new style will not support pg.sql etc.. naming - that's what the direcotries are for..
280 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/sql");
281 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}");
285 if (!empty($this->opts['init']) && file_exists($this->rootDir. "/Pman/$m/{$dbtype}.initdata")) {
286 if (class_exists('PDO_DataObjects_Introspection')) {
287 PDO_DataObject_Introspection::$cache = array();
289 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
291 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}.initdata");
292 $this->{'fixSequences'. $dbtype}();
305 /** -------------- code to handle importing a whole directory of files into the database ------- **/
308 function importpgsqldir($url, $dir, $disable_triggers = false)
310 $ff = HTML_FlexyFramework::get();
312 require_once 'System.php';
313 $cat = System::which('cat');
314 $psql = System::which('psql');
317 if (!empty($url['pass'])) {
318 putenv("PGPASSWORD=". $url['pass']);
322 ' -h ' . $url['host'] .
323 ' -U' . escapeshellarg($url['user']) .
324 ' ' . basename($url['path']);
327 echo $psql_cmd . "\n" ;
328 echo "scan : $dir\n";
331 $files = array($dir);
336 $files = glob($dir.'/*.sql');
337 uksort($files, 'strcasecmp');
339 //$lsort = create_function('$a,$b','return strlen($a) > strlen($b) ? 1 : -1;');
340 //usort($files, $lsort);
343 foreach($files as $bfn) {
346 if (preg_match('/migrate/i', basename($bfn))) { // skip migration scripts at present..
349 if (preg_match('#\.[a-z]{2}\.sql#i', basename($bfn))
350 && !preg_match('#\.pg\.sql#i', basename($bfn))
351 ) { // skip migration scripts at present..
356 if (!preg_match('/pgsql/', basename($dir) )) {
357 if ( !preg_match('#\.pg\.sql$#', basename($bfn))) {
358 $fn = $this->convertToPG($bfn);
362 // files ending in .pg.sql are native postgres files.. ## depricated
365 $cmd = "$psql_cmd < " . escapeshellarg($fn ? $fn : $bfn) . ' 2>&1' ;
367 echo "$bfn: $cmd ". ($ff->cli ? "\n" : "<BR>\n");
383 * mysql - does not support conversions.
387 function importmysqlidir($dburl, $dir) {
388 return $this->importmysqldir($dburl, $dir);
391 function importmysqldir($dburl, $dir)
394 $this->fixMysqlInnodb(); /// run once
396 echo "Import MYSQL :: $dir\n";
399 require_once 'System.php';
400 $cat = System::which('cat');
401 $mysql = System::which('mysql');
405 $mysql_cmd = $mysql .
406 ' -h ' . $dburl['host'] .
407 ' -u' . escapeshellarg($dburl['user']) .
408 (!empty($dburl['pass']) ? ' -p' . escapeshellarg($dburl['pass']) : '') .
409 ' ' . basename($dburl['path']);
410 //echo $mysql_cmd . "\n" ;
412 $files = glob($dir.'/*.sql');
413 uksort($files, 'strcasecmp');
416 foreach($files as $fn) {
419 if (preg_match('/migrate/i', basename($fn))) { // skip migration scripts at present..
422 // .my.sql but not .pg.sql
423 if (preg_match('#\.[a-z]{2}\.sql#i', basename($fn))
424 && !preg_match('#\.my\.sql#i', basename($fn))
425 ) { // skip migration scripts at present..
428 if (!strlen(trim($fn))) {
432 $cmd = "$mysql_cmd -f < " . escapeshellarg($fn) ." 2>&1" ;
434 echo basename($dir).'/'. basename($fn) . '::' . $cmd. ($this->cli ? "\n" : "<BR>\n");
437 $fp = popen($cmd, "r");
440 // send the current file part to the browser
441 $line = trim(fgets($fp, 1024));
446 if (!preg_match('/^ERROR\s+([0-9]+)/', $line, $matches)) {
447 echo " ---- {$line}\n"; flush();
451 switch($matches[1]) {
452 case 1017: // cause by renaming table -- old one does not exist..
453 case 1050: // create tables triggers this..
454 case 1060: // Duplicate column name
455 case 1061: // Duplicate key name - triggered by add index.. but could hide error. - unlikely though.
456 case 1091: // drop index -- name does not exist.. might hide errors..
458 case 1146: // drop a index on an unknown table.. - happens rarely...
459 case 1054: // Unknown column -- triggered by CHANGE COLUMN - but may hide other errrors..
465 echo " ---- {$line}\n"; flush();
469 // 1051: // Unknown table -- normally drop = add iff exists..
470 echo "File: $fn\n$line\n";
486 * simple regex based convert mysql to pgsql...
488 function convertToPG($src)
490 //echo "Convert $src\n";
492 $fn = $this->tempName('sql');
494 $ret = array( ); // pad it a bit.
495 $extra = array("", "" );
498 foreach(file($src) as $l) {
501 if (!strlen($l) || $l[0] == '#') {
505 if (preg_match('#create\s+table\s+([a-z0-9_]+)#i', $l, $m)) {
508 if (preg_match('#create\s+table\s+\`([a-z0-9_]+)\`#i', $l, $m)) {
509 $tbl = 'shop_' . strtolower($m[1]);
510 $l = preg_replace('#create\s+table\s+\`([a-z0-9_]+)\`#i', "CREATE TABLE {$tbl}", $l);
512 if (preg_match('#\`([a-z0-9_]+)\`#i', $l, $m) && !preg_match('#alter\s+table\s+#i', $l)) {
513 $l = preg_replace('#\`([a-z0-9_]+)\`#i', "{$m[1]}_name", $l);
516 if ($tbl && preg_match('#auto_increment#i', $l, $m)) {
517 $l = preg_replace('#auto_increment#i', "default nextval('{$tbl}_seq')", $l);
518 $extra[] = "create sequence {$tbl}_seq;";
522 if (preg_match('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', $l, $m)){
523 $l = preg_replace('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', "ALTER TABLE {$tbl}", $l);
526 // enum value -- use the text instead..
528 if ($tbl && preg_match('#([\w]+)\s+(enum\([\w|\W]+\))#i', $l, $m)) {
529 $l = preg_replace('#enum\([\w|\W]+\)#i', "TEXT", $l);
531 // ignore the alter enum
532 if ($tbl && preg_match('#alter\s+table\s+([\w|\W]+)\s+enum\([\w|\W]+\)#i', $l, $m)) {
536 // UNIQUE KEY .. ignore
537 if ($tbl && preg_match('#UNIQUE KEY#i', $l, $m)) {
538 $last = array_pop($ret);
539 $ret[] = trim($last, ",");
543 if ($tbl && preg_match('#RENAME\s+TO#i', $l, $m)) {
547 if ($tbl && preg_match('#change\s+column#i', $l, $m)) {
551 // INDEX lookup ..ignore
552 if ($tbl && preg_match('#INDEX lookup+([\w|\W]+)#i', $l, $m)) {
553 $last = array_pop($ret);
554 $ret[] = trim($last, ",");
559 // CREATE INDEX ..ignore
560 if (preg_match('#alter\s+table\s+([a-z0-9_]+)\s+add\s+index\s+#i', $l, $m)) {
561 // $l = "CREATE INDEX {$m[1]}_{$m[2]} ON {$m[1]} {$m[3]}";
566 $l = preg_replace('#int\([0-9]+\)#i', 'INT', $l);
568 $l = preg_replace('# datetime#i', ' TIMESTAMP WITHOUT TIME ZONE', $l);
569 $l = preg_replace('# blob#i', ' TEXT', $l);
570 $l = preg_replace('# longtext#i', ' TEXT', $l);
571 $l = preg_replace('# tinyint#i', ' INT', $l);
577 $ret = array_merge($extra,$ret);
578 // echo implode("\n", $ret); exit;
580 file_put_contents($fn, implode("\n", $ret));
586 function checkOpts($opts)
590 foreach($opts as $o=>$v) {
591 if (!preg_match('/^json-/', $o) || empty($v)) {
594 if (!file_exists($v)) {
595 die("File does not exist : OPTION --{$o} = {$v} \n");
599 $modules = array_reverse($this->modulesList());
601 // move 'project' one to the end...
603 foreach ($modules as $module){
604 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
605 if($module == 'Core' || !file_exists($file)){
609 $class = "Pman_{$module}_UpdateDatabase";
611 if(!method_exists($x, 'checkOpts')){
614 $x->checkOpts($opts);
618 static function jsonImportFromArray($opts)
620 foreach($opts as $o=>$v) {
621 if (!preg_match('/^json-/', $o) || empty($v)) {
624 $type = str_replace('_', '-', substr($o,5));
626 $data= json_decode(file_get_contents($v),true);
627 $pg = HTML_FlexyFramework::get()->page;
628 DB_DataObject::factory($type)->importFromArray($pg ,$data,$opts);
638 function runUpdateModulesData()
640 if (class_exists('PDO_DataObjects_Introspection')) {
641 PDO_DataObject_Introspection::$cache = array();
643 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
645 if(!in_array('Core', $this->disabled)){
646 echo "Running jsonImportFromArray\n";
647 Pman_Core_UpdateDatabase::jsonImportFromArray($this->opts);
650 echo "Running updateData on modules\n";
656 $modules = array_reverse($this->modulesList());
658 // move 'project' one to the end...
660 foreach ($modules as $module){
661 if(in_array($module, $this->disabled)){
664 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
665 if($module == 'Core' || !file_exists($file)){
670 $class = "Pman_{$module}_UpdateDatabase";
672 if(!method_exists($x, 'updateData')){
682 function updateDataEnums()
685 $enum = DB_DataObject::Factory('core_enum');
686 //DB_DAtaObject::debugLevel(1);
691 'name' => 'COMPTYPE',
692 'display_name' => 'Company Types',
693 'is_system_enum' => 1,
697 'display_name' => 'Owner',
698 'seqid' => 999, // last...
699 'is_system_enum' => 1,
706 'name' => 'HtmlEditor.font-family',
707 'display_name' => 'HTML Editor font families',
708 'is_system_enum' => 1,
711 'name' => 'Helvetica,Arial,sans-serif',
712 'display_name' => 'Helvetica',
717 'name' => 'Courier New',
718 'display_name' => 'Courier',
723 'display_name' => 'Tahoma',
727 'name' => 'Times New Roman,serif',
728 'display_name' => 'Times',
733 'display_name' => 'Verdana',
745 function updateDataGroups()
748 $groups = DB_DataObject::factory('core_group');
749 $groups->initGroups();
751 $groups->initDatabase($this,array(
753 'name' => 'bcc-email', // group who are bcc'ed on all requests.
754 'type' => 0, // system
757 'name' => 'system-email-from',
758 'type' => 0, // system
761 'name' => 'core-person-signup-bcc',
762 'type' => 0, // system
768 function updateDataCompanies()
771 // fix comptypes enums..
772 $c = DB_DataObject::Factory('core_company');
774 $c->selectAdd('distinct(comptype) as comptype');
775 $c->whereAdd("comptype != ''");
778 foreach($c->fetchAll('comptype') as $cts) {
782 $ctb[]= array( 'etype'=>'COMPTYPE', 'name' => $cts, 'display_name' => ucfirst(strtolower($cts)));
785 $c = DB_DataObject::Factory('core_enum');
788 //DB_DataObject::debugLevel(1);
790 $c = DB_DataObject::Factory('core_company');
792 UPDATE {$c->tableName()}
794 comptype_id = (SELECT id FROM core_enum where etype='comptype' and name={$c->tableName()}.comptype LIMIT 1)
808 function initEmails($templateDir, $emails)
811 $pg = HTML_FlexyFramework::get()->page;
812 foreach($emails as $name=>$data) {
813 $cm = DB_DataObject::factory('core_email');
814 $update = $cm->get('name', $name);
817 if (empty($cm->bcc_group)) {
818 if (empty($data['bcc_group'])) {
819 $this->jerr("missing bcc_group for template $name");
821 $g = DB_DataObject::Factory('core_group')->lookup('name',$data['bcc_group']);
824 $this->jerr("bcc_group {$data['bcc_group']} does not exist when importing template $name");
828 if (!$g->members('email')) {
829 $this->jerr("bcc_group {$data['bcc_group']} does not have any members");
832 $cm->bcc_group = $g->id;
834 if (empty($cm->test_class)) {
835 if (empty($data['test_class'])) {
836 $this->jerr("missing test_class for template $name");
838 $cm->test_class = $data['test_class'];
840 require_once $cm->test_class . '.php';
842 $clsname = str_replace('/','_', $cm->test_class);
844 $method = new ReflectionMethod($clsname , 'test_'. $name) ;
845 $got_it = $method->isStatic();
846 } catch(Exception $e) {
851 $this->jerr("template {$name} does not have a test method {$clsname}::test_{$name}");
855 echo "email: {$name} - checked\n";
856 continue; /// we do not import the body content of templates that exist...
863 // $basedir = $this->bootLoader->rootDir . $mail_template_dir;
867 'file' => $templateDir. $name .'.html'
870 if (!empty($data['master'])) {
871 $opts['master'] = $templateDir . $master .'.html';
873 require_once 'Pman/Core/Import/Core_email.php';
874 $x = new Pman_Core_Import_Core_email();
875 $x->updateOrCreateEmail('', $opts, $cm);
877 echo "email: {$name} - CREATED\n";
882 function updateData()
885 if (class_exists('PDO_DataObjects_Introspection')) {
886 PDO_DataObject_Introspection::$cache = array();
888 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
889 $this->updateDataEnums();
890 $this->updateDataGroups();
891 $this->updateDataCompanies();
893 $c = DB_DataObject::Factory('I18n');
901 function fixMysqlInnodb()
904 static $done_check = false;
908 // innodb in single files is far more efficient that MYD or one big innodb file.
909 // first check if database is using this format.
910 $db = DB_DataObject::factory('core_enum');
911 $db->query("show variables like 'innodb_file_per_table'");
913 if ($db->Value == 'OFF') {
914 die("Error: set innodb_file_per_table = 1 in my.cnf\n\n");
917 $db = DB_DataObject::factory('core_enum');
918 $db->query("select version() as version");
921 if (version_compare($db->version, '5.7', '>=' )) {
923 $db = DB_DataObject::factory('core_enum');
924 $db->query("show variables like 'sql_mode'");
927 $modes = explode(",", $db->Value);
929 // these are 'new' problems with mysql.
931 in_array('NO_ZERO_IN_DATE', $modes) ||
932 in_array('NO_ZERO_DATE', $modes) ||
933 in_array('STRICT_TRANS_TABLES', $modes) ||
934 !in_array('ALLOW_INVALID_DATES', $modes)
936 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");
951 /** ------------- schema fixing ... there is an issue with data imported having the wrong sequence names... --- */
953 function fixSequencesMysql()
958 function fixSequencesPgsql()
962 //DB_DataObject::debugLevel(1);
963 $cs = DB_DataObject::factory('core_enum');
967 CASE WHEN strpos(seq_name, '.') > 0 THEN
970 quote_ident(min(schema_name)) ||'.'|| quote_ident(min(seq_name))
973 ||' OWNED BY '|| quote_ident(min(schema_name)) || '.' ||
974 quote_ident(min(table_name)) ||'.'|| quote_ident(min(column_name)) ||';' as cmd
978 n.nspname AS schema_name,
979 c.relname AS table_name,
980 a.attname AS column_name,
981 regexp_replace(regexp_replace(d.adsrc, E'nextval\\\\(+[''\\\"]*', ''),E'[''\\\"]*::.*\$','') AS seq_name
983 JOIN pg_attribute a ON (c.oid=a.attrelid)
984 JOIN pg_attrdef d ON (a.attrelid=d.adrelid AND a.attnum=d.adnum)
985 JOIN pg_namespace n ON (c.relnamespace=n.oid)
986 WHERE has_schema_privilege(n.oid,'USAGE')
987 AND n.nspname NOT LIKE 'pg!_%' escape '!'
988 AND has_table_privilege(c.oid,'SELECT')
989 AND (NOT a.attisdropped)
990 AND d.adsrc ~ '^nextval'
994 CASE WHEN strpos(seq_name, '.') > 0 THEN
995 substring(seq_name, 1,strpos(seq_name,'.')-1)
1000 GROUP BY seq_name HAVING count(*)=1
1003 while ($cs->fetch()) {
1006 foreach($cmds as $cmd) {
1007 $cs = DB_DataObject::factory('core_enum');
1011 $cs = DB_DataObject::factory('core_enum');
1013 SELECT 'SELECT SETVAL(' ||
1014 quote_literal(quote_ident(nspname) || '.' || quote_ident(S.relname)) ||
1015 ', MAX(' || quote_ident(C.attname)|| ')::integer ) FROM ' || nspname || '.' || quote_ident(T.relname)|| ';' as cmd
1021 WHERE S.relkind = 'S'
1023 AND D.refobjid = T.oid
1024 AND D.refobjid = C.attrelid
1025 AND D.refobjsubid = C.attnum
1026 AND NS.oid = T.relnamespace
1030 while ($cs->fetch()) {
1033 foreach($cmds as $cmd) {
1034 $cs = DB_DataObject::factory('core_enum');
1041 var $extensions = array(
1046 function runExtensions()
1049 $ff = HTML_Flexyframework::get();
1051 $dburl = parse_url($ff->database);
1053 $dbtype = $dburl['scheme'];
1055 foreach($this->extensions as $ext) {
1057 $scls = ucfirst($dbtype). $ext;
1058 $cls = __CLASS__ . '_'. $scls;
1059 $fn = implode('/',explode('_', $cls)).'.php';
1060 if (!file_exists(__DIR__.'/UpdateDatabase/'. $scls .'.php')) {
1071 function checkSystem()
1073 // most of these are from File_Convert...
1075 // these are required - and have simple dependancies.
1076 require_once 'System.php';
1082 'rsvg-convert', //librsvg2-bin
1088 // these are prefered - but may have complicated depenacies
1093 'html2text', // not availabe in debian squeeze
1094 'pdftocairo', //poppler-utils - not available in debian squeeze.
1104 foreach($req as $r) {
1105 if (!System::which($r)) {
1111 die("Missing these programs - need installing\n" . implode("\n",$res). "\n");
1113 foreach($pref as $r) {
1114 if (!System::which($r)) {
1120 echo "WARNING: Missing these programs - they may need installing\n". implode("\n",$res);