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',
72 'json-person' => array(
73 'desc' => 'Person JSON file',
81 static function cli_opts()
84 $ret = self::$cli_opts;
85 $ff = HTML_FlexyFramework::get();
87 $mods = $a->modulesList();
88 foreach($mods as $m) {
90 $fd = $ff->rootDir. "/Pman/$m/UpdateDatabase.php";
91 if (!file_exists($fd)) {
97 $cls = new ReflectionClass('Pman_'. $m . '_UpdateDatabase');
99 $ret = array_merge($ret, $cls->getStaticPropertyValue('cli_opts'));
108 var $disabled = array();
115 $ff = HTML_FlexyFramework::get();
116 if (!empty($ff->cli)) {
121 parent::getAuth(); // load company!
122 $au = $this->getAuthUser();
123 if (!$au || $au->company()->comptype != 'OWNER') {
124 $this->jerr("Not authenticated", array('authFailure' => true));
126 $this->authUser = $au;
130 function get($args, $opts)
132 PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, array($this, 'onPearError'));
134 $this->checkSystem();
136 $ff = HTML_FlexyFramework::get();
138 if(!empty($ff->Core_Notify)){
139 require_once 'Pman/Core/NotifySmtpCheck.php';
140 $x = new Pman_Core_NotifySmtpCheck();
144 $this->disabled = explode(',', $ff->disable);
146 //$this->fixSequencesPgsql();exit;
149 // ask all the modules to verify the opts
151 $this->checkOpts($opts);
153 if (empty($opts['data-only'])) {
156 if (!empty($opts['only-module-sql'])) {
160 $this->runUpdateModulesData();
163 if (!empty($opts['add-company']) && !in_array('Core', $this->disabled)) {
164 // make sure we have a good cache...?
166 DB_DataObject::factory('companies')->initCompanies($this, $opts);
169 $this->runExtensions();
177 * imports SQL files from all DataObjects directories....
179 * except any matching /migrate/
184 // loop through all the modules, and see if they have a importSQL method?
187 $ff = HTML_Flexyframework::get();
189 $dburl = parse_url($ff->DB_DataObject['database']);
191 //$this->{'import' . $url['scheme']}($url);
193 $dbtype = $dburl['scheme'];
194 $dirmethod = 'import' . $dburl['scheme'] . 'dir';
199 $ar = $this->modulesList();
204 if(in_array($m, $this->disabled)){
205 echo "module $m is disabled \n";
209 echo "Importing SQL from module $m\n";
210 if (!empty($this->opts['only-module-sql']) && $m != $this->opts['only-module-sql']) {
215 // check to see if the class has
219 $file = $this->rootDir. "/Pman/$m/UpdateDatabase.php";
220 if($m != 'Core' && file_exists($file)){
223 $class = "Pman_{$m}_UpdateDatabase";
225 if(method_exists($x, 'importModuleSQL')){
226 echo "Importing SQL from module $m using Module::importModuleSQL\n";
227 $x->opts = $this->opts;
228 $x->rootDir = $this->rootDir;
229 $x->importModuleSQL($dburl);
234 echo "Importing SQL from module $m\n";
237 // if init has been called
239 if (!empty($this->opts['init'])) {
240 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}.init");
246 $fd = $this->rootDir. "/Pman/$m/DataObjects";
248 $this->{$dirmethod}($dburl, $fd);
251 // new -- sql directory..
252 // new style will not support migrate ... they have to go into mysql-migrate.... directories..
253 // new style will not support pg.sql etc.. naming - that's what the direcotries are for..
255 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/sql");
256 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}");
260 if (!empty($this->opts['init']) && file_exists($this->rootDir. "/Pman/$m/{$dbtype}.initdata")) {
261 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
263 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}.initdata");
264 $this->{'fixSequences'. $dbtype}();
276 /** -------------- code to handle importing a whole directory of files into the database ------- **/
279 function importpgsqldir($url, $dir, $disable_triggers = false)
281 $ff = HTML_FlexyFramework::get();
283 require_once 'System.php';
284 $cat = System::which('cat');
285 $psql = System::which('psql');
288 if (!empty($url['pass'])) {
289 putenv("PGPASSWORD=". $url['pass']);
293 ' -h ' . $url['host'] .
294 ' -U' . escapeshellarg($url['user']) .
295 ' ' . basename($url['path']);
298 echo $psql_cmd . "\n" ;
299 echo "scan : $dir\n";
302 $files = array($dir);
307 $files = glob($dir.'/*.sql');
308 uksort($files, 'strcasecmp');
310 //$lsort = create_function('$a,$b','return strlen($a) > strlen($b) ? 1 : -1;');
311 //usort($files, $lsort);
314 foreach($files as $bfn) {
317 if (preg_match('/migrate/i', basename($bfn))) { // skip migration scripts at present..
320 if (preg_match('#\.[a-z]{2}\.sql#i', basename($bfn))
321 && !preg_match('#\.pg\.sql#i', basename($bfn))
322 ) { // skip migration scripts at present..
327 if (!preg_match('/pgsql/', basename($dir) )) {
328 if ( !preg_match('#\.pg\.sql$#', basename($bfn))) {
329 $fn = $this->convertToPG($bfn);
333 // files ending in .pg.sql are native postgres files.. ## depricated
336 $cmd = "$psql_cmd < " . escapeshellarg($fn ? $fn : $bfn) . ' 2>&1' ;
338 echo "$bfn: $cmd ". ($ff->cli ? "\n" : "<BR>\n");
354 * mysql - does not support conversions.
360 function importmysqldir($dburl, $dir)
363 $this->fixMysqlInnodb(); /// run once
365 echo "Import MYSQL :: $dir\n";
368 require_once 'System.php';
369 $cat = System::which('cat');
370 $mysql = System::which('mysql');
374 $mysql_cmd = $mysql .
375 ' -h ' . $dburl['host'] .
376 ' -u' . escapeshellarg($dburl['user']) .
377 (!empty($dburl['pass']) ? ' -p' . escapeshellarg($dburl['pass']) : '') .
378 ' ' . basename($dburl['path']);
379 //echo $mysql_cmd . "\n" ;
381 $files = glob($dir.'/*.sql');
382 uksort($files, 'strcasecmp');
385 foreach($files as $fn) {
388 if (preg_match('/migrate/i', basename($fn))) { // skip migration scripts at present..
391 // .my.sql but not .pg.sql
392 if (preg_match('#\.[a-z]{2}\.sql#i', basename($fn))
393 && !preg_match('#\.my\.sql#i', basename($fn))
394 ) { // skip migration scripts at present..
397 if (!strlen(trim($fn))) {
401 $cmd = "$mysql_cmd -f < " . escapeshellarg($fn) ." 2>&1" ;
403 echo basename($dir).'/'. basename($fn) . '::' . $cmd. ($this->cli ? "\n" : "<BR>\n");
406 $fp = popen($cmd, "r");
409 // send the current file part to the browser
410 $line = trim(fgets($fp, 1024));
415 if (!preg_match('/^ERROR\s+([0-9]+)/', $line, $matches)) {
416 echo " ---- {$line}\n"; flush();
420 switch($matches[1]) {
421 case 1017: // cause by renaming table -- old one does not exist..
422 case 1050: // create tables triggers this..
423 case 1060: // Duplicate column name
424 case 1061: // Duplicate key name - triggered by add index.. but could hide error. - unlikely though.
425 case 1091: // drop index -- name does not exist.. might hide errors..
427 case 1146: // drop a index on an unknown table.. - happens rarely...
428 case 1054: // Unknown column -- triggered by CHANGE COLUMN - but may hide other errrors..
434 echo " ---- {$line}\n"; flush();
438 // 1051: // Unknown table -- normally drop = add iff exists..
439 echo "File: $fn\n$line\n";
455 * simple regex based convert mysql to pgsql...
457 function convertToPG($src)
459 //echo "Convert $src\n";
461 $fn = $this->tempName('sql');
463 $ret = array( ); // pad it a bit.
464 $extra = array("", "" );
467 foreach(file($src) as $l) {
470 if (!strlen($l) || $l[0] == '#') {
474 if (preg_match('#create\s+table\s+([a-z0-9_]+)#i', $l, $m)) {
477 if (preg_match('#create\s+table\s+\`([a-z0-9_]+)\`#i', $l, $m)) {
478 $tbl = 'shop_' . strtolower($m[1]);
479 $l = preg_replace('#create\s+table\s+\`([a-z0-9_]+)\`#i', "CREATE TABLE {$tbl}", $l);
481 if (preg_match('#\`([a-z0-9_]+)\`#i', $l, $m) && !preg_match('#alter\s+table\s+#i', $l)) {
482 $l = preg_replace('#\`([a-z0-9_]+)\`#i', "{$m[1]}_name", $l);
485 if ($tbl && preg_match('#auto_increment#i', $l, $m)) {
486 $l = preg_replace('#auto_increment#i', "default nextval('{$tbl}_seq')", $l);
487 $extra[] = "create sequence {$tbl}_seq;";
491 if (preg_match('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', $l, $m)){
492 $l = preg_replace('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', "ALTER TABLE {$tbl}", $l);
495 // enum value -- use the text instead..
497 if ($tbl && preg_match('#([\w]+)\s+(enum\([\w|\W]+\))#i', $l, $m)) {
498 $l = preg_replace('#enum\([\w|\W]+\)#i', "TEXT", $l);
500 // ignore the alter enum
501 if ($tbl && preg_match('#alter\s+table\s+([\w|\W]+)\s+enum\([\w|\W]+\)#i', $l, $m)) {
505 // UNIQUE KEY .. ignore
506 if ($tbl && preg_match('#UNIQUE KEY#i', $l, $m)) {
507 $last = array_pop($ret);
508 $ret[] = trim($last, ",");
512 if ($tbl && preg_match('#RENAME\s+TO#i', $l, $m)) {
516 if ($tbl && preg_match('#change\s+column#i', $l, $m)) {
520 // INDEX lookup ..ignore
521 if ($tbl && preg_match('#INDEX lookup+([\w|\W]+)#i', $l, $m)) {
522 $last = array_pop($ret);
523 $ret[] = trim($last, ",");
528 // CREATE INDEX ..ignore
529 if (preg_match('#alter\s+table\s+([a-z0-9_]+)\s+add\s+index\s+#i', $l, $m)) {
530 // $l = "CREATE INDEX {$m[1]}_{$m[2]} ON {$m[1]} {$m[3]}";
535 $l = preg_replace('#int\([0-9]+\)#i', 'INT', $l);
537 $l = preg_replace('# datetime#i', ' TIMESTAMP WITHOUT TIME ZONE', $l);
538 $l = preg_replace('# blob#i', ' TEXT', $l);
539 $l = preg_replace('# longtext#i', ' TEXT', $l);
540 $l = preg_replace('# tinyint#i', ' INT', $l);
546 $ret = array_merge($extra,$ret);
547 // echo implode("\n", $ret); exit;
549 file_put_contents($fn, implode("\n", $ret));
555 function checkOpts($opts)
559 foreach($opts as $o=>$v) {
560 if (!preg_match('/^json-/', $o) || empty($v)) {
563 if (!file_exists($v)) {
564 die("File does not exist : OPTION --{$o} = {$v} \n");
568 $modules = array_reverse($this->modulesList());
570 // move 'project' one to the end...
572 foreach ($modules as $module){
573 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
574 if($module == 'Core' || !file_exists($file)){
578 $class = "Pman_{$module}_UpdateDatabase";
580 if(!method_exists($x, 'checkOpts')){
583 $x->checkOpts($opts);
587 static function jsonImportFromArray($opts)
589 foreach($opts as $o=>$v) {
590 if (!preg_match('/^json-/', $o) || empty($v)) {
593 $type = str_replace('_', '-', substr($o,5));
595 $data= json_decode(file_get_contents($v),true);
596 $pg = HTML_FlexyFramework::get()->page;
597 DB_DataObject::factory($type)->importFromArray($pg ,$data,$opts);
607 function runUpdateModulesData()
609 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
611 if(!in_array('Core', $this->disabled)){
612 echo "Running jsonImportFromArray\n";
613 Pman_Core_UpdateDatabase::jsonImportFromArray($this->opts);
616 echo "Running updateData on modules\n";
622 $modules = array_reverse($this->modulesList());
624 // move 'project' one to the end...
626 foreach ($modules as $module){
627 if(in_array($module, $this->disabled)){
630 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
631 if($module == 'Core' || !file_exists($file)){
636 $class = "Pman_{$module}_UpdateDatabase";
638 if(!method_exists($x, 'updateData')){
648 function updateDataEnums()
651 $enum = DB_DataObject::Factory('core_enum');
652 //DB_DAtaObject::debugLevel(1);
657 'name' => 'COMPTYPE',
658 'display_name' => 'Company Types',
659 'is_system_enum' => 1,
663 'display_name' => 'Owner',
664 'seqid' => 999, // last...
665 'is_system_enum' => 1,
672 'name' => 'HtmlEditor.font-family',
673 'display_name' => 'HTML Editor font families',
674 'is_system_enum' => 1,
677 'name' => 'Helvetica,Arial,sans-serif',
678 'display_name' => 'Helvetica',
683 'name' => 'Courier New',
684 'display_name' => 'Courier',
689 'display_name' => 'Tahoma',
693 'name' => 'Times New Roman,serif',
694 'display_name' => 'Times',
699 'display_name' => 'Verdana',
711 function updateDataGroups()
714 $groups = DB_DataObject::factory('groups');
715 $groups->initGroups();
717 $groups->initDatabase($this,array(
719 'name' => 'bcc-email', // group who are bcc'ed on all requests.
720 'type' => 0, // system
723 'name' => 'system-email-from',
724 'type' => 0, // system
727 'name' => 'core-person-signup-bcc',
728 'type' => 0, // system
734 function updateDataCompanies()
737 // fix comptypes enums..
738 $c = DB_DataObject::Factory('Companies');
740 $c->selectAdd('distinct(comptype) as comptype');
741 $c->whereAdd("comptype != ''");
744 foreach($c->fetchAll('comptype') as $cts) {
748 $ctb[]= array( 'etype'=>'COMPTYPE', 'name' => $cts, 'display_name' => ucfirst(strtolower($cts)));
751 $c = DB_DataObject::Factory('core_enum');
754 //DB_DataObject::debugLevel(1);
756 $c = DB_DataObject::Factory('Companies');
760 comptype_id = (SELECT id FROM core_enum where etype='comptype' and name=Companies.comptype LIMIT 1)
774 function initEmails($templateDir, $emails)
777 $pg = HTML_FlexyFramework::get()->page;
778 foreach($emails as $name=>$data) {
779 $cm = DB_DataObject::factory('core_email');
780 $update = $cm->get('name', $name);
783 if (empty($cm->bcc_group)) {
784 if (empty($data['bcc_group'])) {
785 $this->jerr("missing bcc_group for template $name");
787 $g = DB_DataObject::Factory('Groups')->lookup('name',$data['bcc_group']);
790 $this->jerr("bcc_group {$data['bcc_group']} does not exist when importing template $name");
792 if (!$g->members('email')) {
793 $this->jerr("bcc_group {$data['bcc_group']} does not have any members");
797 $cm->bcc_group = $g->id;
799 if (empty($cm->test_class)) {
800 if (empty($data['test_class'])) {
801 $this->jerr("missing test_class for template $name");
803 $cm->test_class = $data['test_class'];
805 require_once $cm->test_class . '.php';
807 $clsname = str_replace('/','_', $cm->test_class);
809 $method = new ReflectionMethod($clsname , 'test_'. $name) ;
810 $got_it = $method->isStatic();
811 } catch(Exception $e) {
816 $this->jerr("template {$name} does not have a test method {$clsname}::test_{$name}");
820 echo "email: {$name} - checked\n";
821 continue; /// we do not import the body content of templates that exist...
827 // $basedir = $this->bootLoader->rootDir . $mail_template_dir;
831 'file' => $templateDir. $name .'.html'
834 if (!empty($data['master'])) {
835 $opts['master'] = $templateDir . $master .'.html';
837 require_once 'Pman/Core/Import/Core_email.php';
838 $x = new Pman_Core_Import_Core_email();
841 echo "email: {$name} - CREATED\n";
846 function updateData()
849 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
850 $this->updateDataEnums();
851 $this->updateDataGroups();
852 $this->updateDataCompanies();
854 $c = DB_DataObject::Factory('I18n');
862 function fixMysqlInnodb()
865 static $done_check = false;
869 // innodb in single files is far more efficient that MYD or one big innodb file.
870 // first check if database is using this format.
871 $db = DB_DataObject::factory('core_enum');
872 $db->query("show variables like 'innodb_file_per_table'");
874 if ($db->Value == 'OFF') {
875 die("Error: set innodb_file_per_table = 1 in my.cnf\n\n");
889 /** ------------- schema fixing ... there is an issue with data imported having the wrong sequence names... --- */
891 function fixSequencesMysql()
896 function fixSequencesPgsql()
900 //DB_DataObject::debugLevel(1);
901 $cs = DB_DataObject::factory('core_enum');
905 CASE WHEN strpos(seq_name, '.') > 0 THEN
908 quote_ident(min(schema_name)) ||'.'|| quote_ident(min(seq_name))
911 ||' OWNED BY '|| quote_ident(min(schema_name)) || '.' ||
912 quote_ident(min(table_name)) ||'.'|| quote_ident(min(column_name)) ||';' as cmd
916 n.nspname AS schema_name,
917 c.relname AS table_name,
918 a.attname AS column_name,
919 regexp_replace(regexp_replace(d.adsrc, E'nextval\\\\(+[''\\\"]*', ''),E'[''\\\"]*::.*\$','') AS seq_name
921 JOIN pg_attribute a ON (c.oid=a.attrelid)
922 JOIN pg_attrdef d ON (a.attrelid=d.adrelid AND a.attnum=d.adnum)
923 JOIN pg_namespace n ON (c.relnamespace=n.oid)
924 WHERE has_schema_privilege(n.oid,'USAGE')
925 AND n.nspname NOT LIKE 'pg!_%' escape '!'
926 AND has_table_privilege(c.oid,'SELECT')
927 AND (NOT a.attisdropped)
928 AND d.adsrc ~ '^nextval'
932 CASE WHEN strpos(seq_name, '.') > 0 THEN
933 substring(seq_name, 1,strpos(seq_name,'.')-1)
938 GROUP BY seq_name HAVING count(*)=1
941 while ($cs->fetch()) {
944 foreach($cmds as $cmd) {
945 $cs = DB_DataObject::factory('core_enum');
949 $cs = DB_DataObject::factory('core_enum');
951 SELECT 'SELECT SETVAL(' ||
952 quote_literal(quote_ident(nspname) || '.' || quote_ident(S.relname)) ||
953 ', MAX(' || quote_ident(C.attname)|| ')::integer ) FROM ' || nspname || '.' || quote_ident(T.relname)|| ';' as cmd
959 WHERE S.relkind = 'S'
961 AND D.refobjid = T.oid
962 AND D.refobjid = C.attrelid
963 AND D.refobjsubid = C.attnum
964 AND NS.oid = T.relnamespace
968 while ($cs->fetch()) {
971 foreach($cmds as $cmd) {
972 $cs = DB_DataObject::factory('core_enum');
979 var $extensions = array(
984 function runExtensions()
987 $ff = HTML_Flexyframework::get();
989 $dburl = parse_url($ff->DB_DataObject['database']);
991 $dbtype = $dburl['scheme'];
993 foreach($this->extensions as $ext) {
995 $scls = ucfirst($dbtype). $ext;
996 $cls = __CLASS__ . '_'. $scls;
997 $fn = implode('/',explode('_', $cls)).'.php';
998 if (!file_exists(__DIR__.'/UpdateDatabase/'. $scls .'.php')) {
1009 function checkSystem()
1011 // most of these are from File_Convert...
1013 // these are required - and have simple dependancies.
1014 require_once 'System.php';
1020 'rsvg-convert', //librsvg2-bin
1026 // these are prefered - but may have complicated depenacies
1031 'html2text', // not availabe in debian squeeze
1032 'pdftocairo', //poppler-utils - not available in debian squeeze.
1042 foreach($req as $r) {
1043 if (!System::which($r)) {
1049 $this->jerr("Missing these programs - need installing\n" . implode("\n",$res));
1051 foreach($pref as $r) {
1052 if (!System::which($r)) {
1058 echo "WARNING: Missing these programs - they may need installing\n". implode("\n",$res);