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'])){
147 if(!empty($ff->Core_Notify)){
148 // require_once 'Pman/Core/NotifySmtpCheck.php';
149 // $x = new Pman_Core_NotifySmtpCheck();
153 $this->disabled = explode(',', $ff->disable);
155 //$this->fixSequencesPgsql();exit;
158 // ask all the modules to verify the opts
160 $this->checkOpts($opts);
163 // do this first, so the innodb change + utf8 fixes column max sizes
165 // this will trigger errors about freetext indexes - we will have to remove them manually.?
166 // 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..)
168 $this->runExtensions();
171 if (empty($opts['data-only'])) {
174 if (!empty($opts['only-module-sql'])) {
178 $this->runUpdateModulesData();
181 if (!empty($opts['add-company']) && !in_array('Core', $this->disabled)) {
182 // make sure we have a good cache...?
184 DB_DataObject::factory('core_company')->initCompanies($this, $opts);
187 $this->runExtensions();
195 * imports SQL files from all DataObjects directories....
197 * except any matching /migrate/
202 // loop through all the modules, and see if they have a importSQL method?
205 $ff = HTML_Flexyframework::get();
207 $dburl = parse_url($ff->database); // used to be DB_DataObject['database'] - but not portable to PDO
209 //$this->{'import' . $url['scheme']}($url);
211 $dbtype = $dburl['scheme'];
214 $dirmethod = 'import' . $dburl['scheme'] . 'dir';
219 $ar = $this->modulesList();
224 if(in_array($m, $this->disabled)){
225 echo "module $m is disabled \n";
229 echo "Importing SQL from module $m\n";
230 if (!empty($this->opts['only-module-sql']) && $m != $this->opts['only-module-sql']) {
235 // check to see if the class has
239 $file = $this->rootDir. "/Pman/$m/UpdateDatabase.php";
240 if($m != 'Core' && file_exists($file)){
243 $class = "Pman_{$m}_UpdateDatabase";
245 if(method_exists($x, 'importModuleSQL')){
246 echo "Importing SQL from module $m using Module::importModuleSQL\n";
247 $x->opts = $this->opts;
248 $x->rootDir = $this->rootDir;
249 $x->importModuleSQL($dburl);
254 echo "Importing SQL from module $m\n";
257 // if init has been called
259 if (!empty($this->opts['init'])) {
260 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}.init");
266 $fd = $this->rootDir. "/Pman/$m/DataObjects";
268 $this->{$dirmethod}($dburl, $fd);
271 // new -- sql directory..
272 // new style will not support migrate ... they have to go into mysql-migrate.... directories..
273 // new style will not support pg.sql etc.. naming - that's what the direcotries are for..
275 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/sql");
276 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}");
280 if (!empty($this->opts['init']) && file_exists($this->rootDir. "/Pman/$m/{$dbtype}.initdata")) {
281 if (class_exists('PDO_DataObjects_Introspection')) {
282 PDO_DataObject_Introspection::$cache = array();
284 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
286 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}.initdata");
287 $this->{'fixSequences'. $dbtype}();
300 /** -------------- code to handle importing a whole directory of files into the database ------- **/
303 function importpgsqldir($url, $dir, $disable_triggers = false)
305 $ff = HTML_FlexyFramework::get();
307 require_once 'System.php';
308 $cat = System::which('cat');
309 $psql = System::which('psql');
312 if (!empty($url['pass'])) {
313 putenv("PGPASSWORD=". $url['pass']);
317 ' -h ' . $url['host'] .
318 ' -U' . escapeshellarg($url['user']) .
319 ' ' . basename($url['path']);
322 echo $psql_cmd . "\n" ;
323 echo "scan : $dir\n";
326 $files = array($dir);
331 $files = glob($dir.'/*.sql');
332 uksort($files, 'strcasecmp');
334 //$lsort = create_function('$a,$b','return strlen($a) > strlen($b) ? 1 : -1;');
335 //usort($files, $lsort);
338 foreach($files as $bfn) {
341 if (preg_match('/migrate/i', basename($bfn))) { // skip migration scripts at present..
344 if (preg_match('#\.[a-z]{2}\.sql#i', basename($bfn))
345 && !preg_match('#\.pg\.sql#i', basename($bfn))
346 ) { // skip migration scripts at present..
351 if (!preg_match('/pgsql/', basename($dir) )) {
352 if ( !preg_match('#\.pg\.sql$#', basename($bfn))) {
353 $fn = $this->convertToPG($bfn);
357 // files ending in .pg.sql are native postgres files.. ## depricated
360 $cmd = "$psql_cmd < " . escapeshellarg($fn ? $fn : $bfn) . ' 2>&1' ;
362 echo "$bfn: $cmd ". ($ff->cli ? "\n" : "<BR>\n");
378 * mysql - does not support conversions.
382 function importmysqlidir($dburl, $dir) {
383 return $this->importmysqldir($dburl, $dir);
386 function importmysqldir($dburl, $dir)
389 $this->fixMysqlInnodb(); /// run once
391 echo "Import MYSQL :: $dir\n";
394 require_once 'System.php';
395 $cat = System::which('cat');
396 $mysql = System::which('mysql');
400 $mysql_cmd = $mysql .
401 ' -h ' . $dburl['host'] .
402 ' -u' . escapeshellarg($dburl['user']) .
403 (!empty($dburl['pass']) ? ' -p' . escapeshellarg($dburl['pass']) : '') .
404 ' ' . basename($dburl['path']);
405 //echo $mysql_cmd . "\n" ;
407 $files = glob($dir.'/*.sql');
408 uksort($files, 'strcasecmp');
411 foreach($files as $fn) {
414 if (preg_match('/migrate/i', basename($fn))) { // skip migration scripts at present..
417 // .my.sql but not .pg.sql
418 if (preg_match('#\.[a-z]{2}\.sql#i', basename($fn))
419 && !preg_match('#\.my\.sql#i', basename($fn))
420 ) { // skip migration scripts at present..
423 if (!strlen(trim($fn))) {
427 $cmd = "$mysql_cmd -f < " . escapeshellarg($fn) ." 2>&1" ;
429 echo basename($dir).'/'. basename($fn) . '::' . $cmd. ($this->cli ? "\n" : "<BR>\n");
432 $fp = popen($cmd, "r");
435 // send the current file part to the browser
436 $line = trim(fgets($fp, 1024));
441 if (!preg_match('/^ERROR\s+([0-9]+)/', $line, $matches)) {
442 echo " ---- {$line}\n"; flush();
446 switch($matches[1]) {
447 case 1017: // cause by renaming table -- old one does not exist..
448 case 1050: // create tables triggers this..
449 case 1060: // Duplicate column name
450 case 1061: // Duplicate key name - triggered by add index.. but could hide error. - unlikely though.
451 case 1091: // drop index -- name does not exist.. might hide errors..
453 case 1146: // drop a index on an unknown table.. - happens rarely...
454 case 1054: // Unknown column -- triggered by CHANGE COLUMN - but may hide other errrors..
460 echo " ---- {$line}\n"; flush();
464 // 1051: // Unknown table -- normally drop = add iff exists..
465 echo "File: $fn\n$line\n";
481 * simple regex based convert mysql to pgsql...
483 function convertToPG($src)
485 //echo "Convert $src\n";
487 $fn = $this->tempName('sql');
489 $ret = array( ); // pad it a bit.
490 $extra = array("", "" );
493 foreach(file($src) as $l) {
496 if (!strlen($l) || $l[0] == '#') {
500 if (preg_match('#create\s+table\s+([a-z0-9_]+)#i', $l, $m)) {
503 if (preg_match('#create\s+table\s+\`([a-z0-9_]+)\`#i', $l, $m)) {
504 $tbl = 'shop_' . strtolower($m[1]);
505 $l = preg_replace('#create\s+table\s+\`([a-z0-9_]+)\`#i', "CREATE TABLE {$tbl}", $l);
507 if (preg_match('#\`([a-z0-9_]+)\`#i', $l, $m) && !preg_match('#alter\s+table\s+#i', $l)) {
508 $l = preg_replace('#\`([a-z0-9_]+)\`#i', "{$m[1]}_name", $l);
511 if ($tbl && preg_match('#auto_increment#i', $l, $m)) {
512 $l = preg_replace('#auto_increment#i', "default nextval('{$tbl}_seq')", $l);
513 $extra[] = "create sequence {$tbl}_seq;";
517 if (preg_match('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', $l, $m)){
518 $l = preg_replace('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', "ALTER TABLE {$tbl}", $l);
521 // enum value -- use the text instead..
523 if ($tbl && preg_match('#([\w]+)\s+(enum\([\w|\W]+\))#i', $l, $m)) {
524 $l = preg_replace('#enum\([\w|\W]+\)#i', "TEXT", $l);
526 // ignore the alter enum
527 if ($tbl && preg_match('#alter\s+table\s+([\w|\W]+)\s+enum\([\w|\W]+\)#i', $l, $m)) {
531 // UNIQUE KEY .. ignore
532 if ($tbl && preg_match('#UNIQUE KEY#i', $l, $m)) {
533 $last = array_pop($ret);
534 $ret[] = trim($last, ",");
538 if ($tbl && preg_match('#RENAME\s+TO#i', $l, $m)) {
542 if ($tbl && preg_match('#change\s+column#i', $l, $m)) {
546 // INDEX lookup ..ignore
547 if ($tbl && preg_match('#INDEX lookup+([\w|\W]+)#i', $l, $m)) {
548 $last = array_pop($ret);
549 $ret[] = trim($last, ",");
554 // CREATE INDEX ..ignore
555 if (preg_match('#alter\s+table\s+([a-z0-9_]+)\s+add\s+index\s+#i', $l, $m)) {
556 // $l = "CREATE INDEX {$m[1]}_{$m[2]} ON {$m[1]} {$m[3]}";
561 $l = preg_replace('#int\([0-9]+\)#i', 'INT', $l);
563 $l = preg_replace('# datetime#i', ' TIMESTAMP WITHOUT TIME ZONE', $l);
564 $l = preg_replace('# blob#i', ' TEXT', $l);
565 $l = preg_replace('# longtext#i', ' TEXT', $l);
566 $l = preg_replace('# tinyint#i', ' INT', $l);
572 $ret = array_merge($extra,$ret);
573 // echo implode("\n", $ret); exit;
575 file_put_contents($fn, implode("\n", $ret));
581 function checkOpts($opts)
585 foreach($opts as $o=>$v) {
586 if (!preg_match('/^json-/', $o) || empty($v)) {
589 if (!file_exists($v)) {
590 die("File does not exist : OPTION --{$o} = {$v} \n");
594 $modules = array_reverse($this->modulesList());
596 // move 'project' one to the end...
598 foreach ($modules as $module){
599 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
600 if($module == 'Core' || !file_exists($file)){
604 $class = "Pman_{$module}_UpdateDatabase";
606 if(!method_exists($x, 'checkOpts')){
609 $x->checkOpts($opts);
613 static function jsonImportFromArray($opts)
615 foreach($opts as $o=>$v) {
616 if (!preg_match('/^json-/', $o) || empty($v)) {
619 $type = str_replace('_', '-', substr($o,5));
621 $data= json_decode(file_get_contents($v),true);
622 $pg = HTML_FlexyFramework::get()->page;
623 DB_DataObject::factory($type)->importFromArray($pg ,$data,$opts);
633 function runUpdateModulesData()
635 if (class_exists('PDO_DataObjects_Introspection')) {
636 PDO_DataObject_Introspection::$cache = array();
638 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
640 if(!in_array('Core', $this->disabled)){
641 echo "Running jsonImportFromArray\n";
642 Pman_Core_UpdateDatabase::jsonImportFromArray($this->opts);
645 echo "Running updateData on modules\n";
651 $modules = array_reverse($this->modulesList());
653 // move 'project' one to the end...
655 foreach ($modules as $module){
656 if(in_array($module, $this->disabled)){
659 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
660 if($module == 'Core' || !file_exists($file)){
665 $class = "Pman_{$module}_UpdateDatabase";
667 if(!method_exists($x, 'updateData')){
677 function updateDataEnums()
680 $enum = DB_DataObject::Factory('core_enum');
681 //DB_DAtaObject::debugLevel(1);
686 'name' => 'COMPTYPE',
687 'display_name' => 'Company Types',
688 'is_system_enum' => 1,
692 'display_name' => 'Owner',
693 'seqid' => 999, // last...
694 'is_system_enum' => 1,
701 'name' => 'HtmlEditor.font-family',
702 'display_name' => 'HTML Editor font families',
703 'is_system_enum' => 1,
706 'name' => 'Helvetica,Arial,sans-serif',
707 'display_name' => 'Helvetica',
712 'name' => 'Courier New',
713 'display_name' => 'Courier',
718 'display_name' => 'Tahoma',
722 'name' => 'Times New Roman,serif',
723 'display_name' => 'Times',
728 'display_name' => 'Verdana',
740 function updateDataGroups()
743 $groups = DB_DataObject::factory('core_group');
744 $groups->initGroups();
746 $groups->initDatabase($this,array(
748 'name' => 'bcc-email', // group who are bcc'ed on all requests.
749 'type' => 0, // system
752 'name' => 'system-email-from',
753 'type' => 0, // system
756 'name' => 'core-person-signup-bcc',
757 'type' => 0, // system
763 function updateDataCompanies()
766 // fix comptypes enums..
767 $c = DB_DataObject::Factory('core_company');
769 $c->selectAdd('distinct(comptype) as comptype');
770 $c->whereAdd("comptype != ''");
773 foreach($c->fetchAll('comptype') as $cts) {
777 $ctb[]= array( 'etype'=>'COMPTYPE', 'name' => $cts, 'display_name' => ucfirst(strtolower($cts)));
780 $c = DB_DataObject::Factory('core_enum');
783 //DB_DataObject::debugLevel(1);
785 $c = DB_DataObject::Factory('core_company');
787 UPDATE {$c->tableName()}
789 comptype_id = (SELECT id FROM core_enum where etype='comptype' and name={$c->tableName()}.comptype LIMIT 1)
803 function initEmails($templateDir, $emails)
806 $pg = HTML_FlexyFramework::get()->page;
807 foreach($emails as $name=>$data) {
808 $cm = DB_DataObject::factory('core_email');
809 $update = $cm->get('name', $name);
812 if (empty($cm->bcc_group)) {
813 if (empty($data['bcc_group'])) {
814 $this->jerr("missing bcc_group for template $name");
816 $g = DB_DataObject::Factory('core_group')->lookup('name',$data['bcc_group']);
819 $this->jerr("bcc_group {$data['bcc_group']} does not exist when importing template $name");
823 if (!$g->members('email')) {
824 $this->jerr("bcc_group {$data['bcc_group']} does not have any members");
827 $cm->bcc_group = $g->id;
829 if (empty($cm->test_class)) {
830 if (empty($data['test_class'])) {
831 $this->jerr("missing test_class for template $name");
833 $cm->test_class = $data['test_class'];
835 require_once $cm->test_class . '.php';
837 $clsname = str_replace('/','_', $cm->test_class);
839 $method = new ReflectionMethod($clsname , 'test_'. $name) ;
840 $got_it = $method->isStatic();
841 } catch(Exception $e) {
846 $this->jerr("template {$name} does not have a test method {$clsname}::test_{$name}");
850 echo "email: {$name} - checked\n";
851 continue; /// we do not import the body content of templates that exist...
858 // $basedir = $this->bootLoader->rootDir . $mail_template_dir;
862 'file' => $templateDir. $name .'.html'
865 if (!empty($data['master'])) {
866 $opts['master'] = $templateDir . $master .'.html';
868 require_once 'Pman/Core/Import/Core_email.php';
869 $x = new Pman_Core_Import_Core_email();
870 $x->updateOrCreateEmail('', $opts, $cm);
872 echo "email: {$name} - CREATED\n";
877 function updateData()
880 if (class_exists('PDO_DataObjects_Introspection')) {
881 PDO_DataObject_Introspection::$cache = array();
883 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
884 $this->updateDataEnums();
885 $this->updateDataGroups();
886 $this->updateDataCompanies();
888 $c = DB_DataObject::Factory('I18n');
896 function fixMysqlInnodb()
899 static $done_check = false;
903 // innodb in single files is far more efficient that MYD or one big innodb file.
904 // first check if database is using this format.
905 $db = DB_DataObject::factory('core_enum');
906 $db->query("show variables like 'innodb_file_per_table'");
908 if ($db->Value == 'OFF') {
909 die("Error: set innodb_file_per_table = 1 in my.cnf\n\n");
912 $db = DB_DataObject::factory('core_enum');
913 $db->query("select version() as version");
916 if (version_compare($db->version, '5.7', '>=' )) {
918 $db = DB_DataObject::factory('core_enum');
919 $db->query("show variables like 'sql_mode'");
922 $modes = explode(",", $db->Value);
924 // these are 'new' problems with mysql.
926 in_array('NO_ZERO_IN_DATE', $modes) ||
927 in_array('NO_ZERO_DATE', $modes) ||
928 in_array('STRICT_TRANS_TABLES', $modes) ||
929 !in_array('ALLOW_INVALID_DATES', $modes)
931 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");
946 /** ------------- schema fixing ... there is an issue with data imported having the wrong sequence names... --- */
948 function fixSequencesMysql()
953 function fixSequencesPgsql()
957 //DB_DataObject::debugLevel(1);
958 $cs = DB_DataObject::factory('core_enum');
962 CASE WHEN strpos(seq_name, '.') > 0 THEN
965 quote_ident(min(schema_name)) ||'.'|| quote_ident(min(seq_name))
968 ||' OWNED BY '|| quote_ident(min(schema_name)) || '.' ||
969 quote_ident(min(table_name)) ||'.'|| quote_ident(min(column_name)) ||';' as cmd
973 n.nspname AS schema_name,
974 c.relname AS table_name,
975 a.attname AS column_name,
976 regexp_replace(regexp_replace(d.adsrc, E'nextval\\\\(+[''\\\"]*', ''),E'[''\\\"]*::.*\$','') AS seq_name
978 JOIN pg_attribute a ON (c.oid=a.attrelid)
979 JOIN pg_attrdef d ON (a.attrelid=d.adrelid AND a.attnum=d.adnum)
980 JOIN pg_namespace n ON (c.relnamespace=n.oid)
981 WHERE has_schema_privilege(n.oid,'USAGE')
982 AND n.nspname NOT LIKE 'pg!_%' escape '!'
983 AND has_table_privilege(c.oid,'SELECT')
984 AND (NOT a.attisdropped)
985 AND d.adsrc ~ '^nextval'
989 CASE WHEN strpos(seq_name, '.') > 0 THEN
990 substring(seq_name, 1,strpos(seq_name,'.')-1)
995 GROUP BY seq_name HAVING count(*)=1
998 while ($cs->fetch()) {
1001 foreach($cmds as $cmd) {
1002 $cs = DB_DataObject::factory('core_enum');
1006 $cs = DB_DataObject::factory('core_enum');
1008 SELECT 'SELECT SETVAL(' ||
1009 quote_literal(quote_ident(nspname) || '.' || quote_ident(S.relname)) ||
1010 ', MAX(' || quote_ident(C.attname)|| ')::integer ) FROM ' || nspname || '.' || quote_ident(T.relname)|| ';' as cmd
1016 WHERE S.relkind = 'S'
1018 AND D.refobjid = T.oid
1019 AND D.refobjid = C.attrelid
1020 AND D.refobjsubid = C.attnum
1021 AND NS.oid = T.relnamespace
1025 while ($cs->fetch()) {
1028 foreach($cmds as $cmd) {
1029 $cs = DB_DataObject::factory('core_enum');
1036 var $extensions = array(
1041 function runExtensions()
1044 $ff = HTML_Flexyframework::get();
1046 $dburl = parse_url($ff->database);
1048 $dbtype = $dburl['scheme'];
1050 foreach($this->extensions as $ext) {
1052 $scls = ucfirst($dbtype). $ext;
1053 $cls = __CLASS__ . '_'. $scls;
1054 $fn = implode('/',explode('_', $cls)).'.php';
1055 if (!file_exists(__DIR__.'/UpdateDatabase/'. $scls .'.php')) {
1066 function checkSystem()
1068 // most of these are from File_Convert...
1070 // these are required - and have simple dependancies.
1071 require_once 'System.php';
1077 'rsvg-convert', //librsvg2-bin
1083 // these are prefered - but may have complicated depenacies
1088 'html2text', // not availabe in debian squeeze
1089 'pdftocairo', //poppler-utils - not available in debian squeeze.
1099 foreach($req as $r) {
1100 if (!System::which($r)) {
1106 die("Missing these programs - need installing\n" . implode("\n",$res). "\n");
1108 foreach($pref as $r) {
1109 if (!System::which($r)) {
1115 echo "WARNING: Missing these programs - they may need installing\n". implode("\n",$res);