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();
140 $this->disabled = explode(',', $ff->disable);
142 //$this->fixSequencesPgsql();exit;
145 // ask all the modules to verify the opts
147 $this->checkOpts($opts);
149 if (empty($opts['data-only'])) {
152 if (!empty($opts['only-module-sql'])) {
156 $this->runUpdateModulesData();
159 if (!empty($opts['add-company']) && !in_array('Core', $this->disabled)) {
160 // make sure we have a good cache...?
162 DB_DataObject::factory('companies')->initCompanies($this, $opts);
165 $this->runExtensions();
173 * imports SQL files from all DataObjects directories....
175 * except any matching /migrate/
180 // loop through all the modules, and see if they have a importSQL method?
183 $ff = HTML_Flexyframework::get();
185 $dburl = parse_url($ff->DB_DataObject['database']);
187 //$this->{'import' . $url['scheme']}($url);
189 $dbtype = $dburl['scheme'];
190 $dirmethod = 'import' . $dburl['scheme'] . 'dir';
195 $ar = $this->modulesList();
199 if(in_array($m, $this->disabled)){
200 echo "module $m is disabled \n";
204 echo "Importing SQL from module $m\n";
205 if (!empty($this->opts['only-module-sql']) && $m != $this->opts['only-module-sql']) {
210 // check to see if the class has
214 $file = $this->rootDir. "/Pman/$m/UpdateDatabase.php";
215 if($m != 'Core' && file_exists($file)){
218 $class = "Pman_{$m}_UpdateDatabase";
220 if(method_exists($x, 'importModuleSQL')){
221 echo "Importing SQL from module $m using Module::importModuleSQL\n";
222 $x->opts = $this->opts;
223 $x->rootDir = $this->rootDir;
224 $x->importModuleSQL($dburl);
229 echo "Importing SQL from module $m\n";
232 // if init has been called
234 if (!empty($this->opts['init'])) {
235 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}.init");
241 $fd = $this->rootDir. "/Pman/$m/DataObjects";
243 $this->{$dirmethod}($dburl, $fd);
246 // new -- sql directory..
247 // new style will not support migrate ... they have to go into mysql-migrate.... directories..
248 // new style will not support pg.sql etc.. naming - that's what the direcotries are for..
250 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/sql");
251 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}");
255 if (!empty($this->opts['init']) && file_exists($this->rootDir. "/Pman/$m/{$dbtype}.initdata")) {
256 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
258 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}.initdata");
259 $this->{'fixSequences'. $dbtype}();
271 /** -------------- code to handle importing a whole directory of files into the database ------- **/
274 function importpgsqldir($url, $dir, $disable_triggers = false)
276 $ff = HTML_FlexyFramework::get();
278 require_once 'System.php';
279 $cat = System::which('cat');
280 $psql = System::which('psql');
283 if (!empty($url['pass'])) {
284 putenv("PGPASSWORD=". $url['pass']);
288 ' -h ' . $url['host'] .
289 ' -U' . escapeshellarg($url['user']) .
290 ' ' . basename($url['path']);
293 echo $psql_cmd . "\n" ;
294 echo "scan : $dir\n";
297 $files = array($dir);
302 $files = glob($dir.'/*.sql');
303 uksort($files, 'strcasecmp');
305 //$lsort = create_function('$a,$b','return strlen($a) > strlen($b) ? 1 : -1;');
306 //usort($files, $lsort);
309 foreach($files as $bfn) {
312 if (preg_match('/migrate/i', basename($bfn))) { // skip migration scripts at present..
315 if (preg_match('#\.[a-z]{2}\.sql#i', basename($bfn))
316 && !preg_match('#\.pg\.sql#i', basename($bfn))
317 ) { // skip migration scripts at present..
322 if (!preg_match('/pgsql/', basename($dir) )) {
323 if ( !preg_match('#\.pg\.sql$#', basename($bfn))) {
324 $fn = $this->convertToPG($bfn);
328 // files ending in .pg.sql are native postgres files.. ## depricated
331 $cmd = "$psql_cmd < " . escapeshellarg($fn ? $fn : $bfn) . ' 2>&1' ;
333 echo "$bfn: $cmd ". ($ff->cli ? "\n" : "<BR>\n");
349 * mysql - does not support conversions.
355 function importmysqldir($dburl, $dir)
358 $this->fixMysqlInnodb(); /// run once
360 echo "Import MYSQL :: $dir\n";
363 require_once 'System.php';
364 $cat = System::which('cat');
365 $mysql = System::which('mysql');
369 $mysql_cmd = $mysql .
370 ' -h ' . $dburl['host'] .
371 ' -u' . escapeshellarg($dburl['user']) .
372 (!empty($dburl['pass']) ? ' -p' . escapeshellarg($dburl['pass']) : '') .
373 ' ' . basename($dburl['path']);
374 //echo $mysql_cmd . "\n" ;
376 $files = glob($dir.'/*.sql');
377 uksort($files, 'strcasecmp');
380 foreach($files as $fn) {
383 if (preg_match('/migrate/i', basename($fn))) { // skip migration scripts at present..
386 // .my.sql but not .pg.sql
387 if (preg_match('#\.[a-z]{2}\.sql#i', basename($fn))
388 && !preg_match('#\.my\.sql#i', basename($fn))
389 ) { // skip migration scripts at present..
392 if (!strlen(trim($fn))) {
396 $cmd = "$mysql_cmd -f < " . escapeshellarg($fn) ;
398 echo basename($dir).'/'. basename($fn) . '::' . $cmd. ($this->cli ? "\n" : "<BR>\n");
411 * simple regex based convert mysql to pgsql...
413 function convertToPG($src)
415 //echo "Convert $src\n";
417 $fn = $this->tempName('sql');
419 $ret = array( ); // pad it a bit.
420 $extra = array("", "" );
423 foreach(file($src) as $l) {
426 if (!strlen($l) || $l[0] == '#') {
430 if (preg_match('#create\s+table\s+([a-z0-9_]+)#i', $l, $m)) {
433 if (preg_match('#create\s+table\s+\`([a-z0-9_]+)\`#i', $l, $m)) {
434 $tbl = 'shop_' . strtolower($m[1]);
435 $l = preg_replace('#create\s+table\s+\`([a-z0-9_]+)\`#i', "CREATE TABLE {$tbl}", $l);
437 if (preg_match('#\`([a-z0-9_]+)\`#i', $l, $m) && !preg_match('#alter\s+table\s+#i', $l)) {
438 $l = preg_replace('#\`([a-z0-9_]+)\`#i', "{$m[1]}_name", $l);
441 if ($tbl && preg_match('#auto_increment#i', $l, $m)) {
442 $l = preg_replace('#auto_increment#i', "default nextval('{$tbl}_seq')", $l);
443 $extra[] = "create sequence {$tbl}_seq;";
447 if (preg_match('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', $l, $m)){
448 $l = preg_replace('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', "ALTER TABLE {$tbl}", $l);
451 // enum value -- use the text instead..
453 if ($tbl && preg_match('#([\w]+)\s+(enum\([\w|\W]+\))#i', $l, $m)) {
454 $l = preg_replace('#enum\([\w|\W]+\)#i', "TEXT", $l);
456 // ignore the alter enum
457 if ($tbl && preg_match('#alter\s+table\s+([\w|\W]+)\s+enum\([\w|\W]+\)#i', $l, $m)) {
461 // UNIQUE KEY .. ignore
462 if ($tbl && preg_match('#UNIQUE KEY#i', $l, $m)) {
463 $last = array_pop($ret);
464 $ret[] = trim($last, ",");
468 if ($tbl && preg_match('#RENAME\s+TO#i', $l, $m)) {
472 if ($tbl && preg_match('#change\s+column#i', $l, $m)) {
476 // INDEX lookup ..ignore
477 if ($tbl && preg_match('#INDEX lookup+([\w|\W]+)#i', $l, $m)) {
478 $last = array_pop($ret);
479 $ret[] = trim($last, ",");
484 // CREATE INDEX ..ignore
485 if (preg_match('#alter\s+table\s+([a-z0-9_]+)\s+add\s+index\s+#i', $l, $m)) {
486 // $l = "CREATE INDEX {$m[1]}_{$m[2]} ON {$m[1]} {$m[3]}";
491 $l = preg_replace('#int\([0-9]+\)#i', 'INT', $l);
493 $l = preg_replace('# datetime#i', ' TIMESTAMP WITHOUT TIME ZONE', $l);
494 $l = preg_replace('# blob#i', ' TEXT', $l);
495 $l = preg_replace('# longtext#i', ' TEXT', $l);
496 $l = preg_replace('# tinyint#i', ' INT', $l);
502 $ret = array_merge($extra,$ret);
503 // echo implode("\n", $ret); exit;
505 file_put_contents($fn, implode("\n", $ret));
511 function checkOpts($opts)
515 foreach($opts as $o=>$v) {
516 if (!preg_match('/^json-/', $o) || empty($v)) {
519 if (!file_exists($v)) {
520 die("File does not exist : OPTION --{$o} = {$v} \n");
524 $modules = array_reverse($this->modulesList());
526 // move 'project' one to the end...
528 foreach ($modules as $module){
529 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
530 if($module == 'Core' || !file_exists($file)){
534 $class = "Pman_{$module}_UpdateDatabase";
536 if(!method_exists($x, 'checkOpts')){
539 $x->checkOpts($opts);
543 static function jsonImportFromArray($opts)
545 foreach($opts as $o=>$v) {
546 if (!preg_match('/^json-/', $o) || empty($v)) {
549 $type = str_replace('_', '-', substr($o,5));
551 $data= json_decode(file_get_contents($v),true);
552 $pg = HTML_FlexyFramework::get()->page;
553 DB_DataObject::factory($type)->importFromArray($pg ,$data,$opts);
563 function runUpdateModulesData()
565 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
567 if(!in_array('Core', $this->disabled)){
568 echo "Running jsonImportFromArray\n";
569 Pman_Core_UpdateDatabase::jsonImportFromArray($this->opts);
572 echo "Running updateData on modules\n";
578 $modules = array_reverse($this->modulesList());
580 // move 'project' one to the end...
582 foreach ($modules as $module){
583 if(in_array($module, $this->disabled)){
586 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
587 if($module == 'Core' || !file_exists($file)){
592 $class = "Pman_{$module}_UpdateDatabase";
594 if(!method_exists($x, 'updateData')){
604 function updateDataEnums()
607 $enum = DB_DataObject::Factory('core_enum');
608 //DB_DAtaObject::debugLevel(1);
613 'name' => 'COMPTYPE',
614 'display_name' => 'Company Types',
615 'is_system_enum' => 1,
619 'display_name' => 'Owner',
620 'seqid' => 999, // last...
621 'is_system_enum' => 1,
628 'name' => 'HtmlEditor.font-family',
629 'display_name' => 'HTML Editor font families',
630 'is_system_enum' => 1,
633 'name' => 'Helvetica,Arial,sans-serif',
634 'display_name' => 'Helvetica',
639 'name' => 'Courier New',
640 'display_name' => 'Courier',
645 'display_name' => 'Tahoma',
649 'name' => 'Times New Roman,serif',
650 'display_name' => 'Times',
655 'display_name' => 'Verdana',
667 function updateDataGroups()
670 $groups = DB_DataObject::factory('groups');
671 $groups->initGroups();
673 $groups->initDatabase($this,array(
675 'name' => 'bcc-email', // group who are bcc'ed on all requests.
676 'type' => 0, // system
679 'name' => 'system-email-from',
680 'type' => 0, // system
683 'name' => 'core-person-signup-bcc',
684 'type' => 0, // system
690 function updateDataCompanies()
693 // fix comptypes enums..
694 $c = DB_DataObject::Factory('Companies');
696 $c->selectAdd('distinct(comptype) as comptype');
697 $c->whereAdd("comptype != ''");
700 foreach($c->fetchAll('comptype') as $cts) {
704 $ctb[]= array( 'etype'=>'COMPTYPE', 'name' => $cts, 'display_name' => ucfirst(strtolower($cts)));
707 $c = DB_DataObject::Factory('core_enum');
710 //DB_DataObject::debugLevel(1);
712 $c = DB_DataObject::Factory('Companies');
716 comptype_id = (SELECT id FROM core_enum where etype='comptype' and name=Companies.comptype LIMIT 1)
730 function initEmails($templateDir, $emails)
733 $pg = HTML_FlexyFramework::get()->page;
734 foreach($emails as $name=>$data) {
735 $cm = DB_DataObject::factory('core_email');
736 $update = $cm->get('name', $name);
739 if (empty($cm->bcc_group)) {
740 if (empty($data['bcc_group'])) {
741 $this->jerr("missing bcc_group for template $name");
743 $g = DB_DataObject::Factory('Groups')->lookup('name',$data['bcc_group']);
746 $this->jerr("bcc_group {$data['bcc_group']} does not exist when importing template $name");
748 if (!$g->members('email')) {
749 $this->jerr("bcc_group {$data['bcc_group']} does not have any members");
753 $cm->bcc_group = $g->id;
755 if (empty($cm->test_class)) {
756 if (empty($data['test_class'])) {
757 $this->jerr("missing test_class for template $name");
759 $cm->test_class = $data['test_class'];
761 require_once $cm->test_class . '.php';
763 $clsname = str_replace('/','_', $cm->test_class);
765 $method = new ReflectionMethod($clsname , 'test_'. $name) ;
766 $got_it = $method->isStatic();
767 } catch(Exception $e) {
772 $this->jerr("template {$name} does not have a test method {$clsname}::test_{$name}");
776 echo "email: {$name} - checked\n";
777 continue; /// we do not import the body content of templates that exist...
783 // $basedir = $this->bootLoader->rootDir . $mail_template_dir;
787 'file' => $templateDir. $name .'.html'
790 if (!empty($data['master'])) {
791 $opts['master'] = $templateDir . $master .'.html';
793 require_once 'Pman/Core/Import/Core_email.php';
794 $x = new Pman_Core_Import_Core_email();
797 echo "email: {$name} - CREATED\n";
802 function updateData()
805 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
806 $this->updateDataEnums();
807 $this->updateDataGroups();
808 $this->updateDataCompanies();
810 $c = DB_DataObject::Factory('I18n');
818 function fixMysqlInnodb()
821 static $done_check = false;
825 // innodb in single files is far more efficient that MYD or one big innodb file.
826 // first check if database is using this format.
827 $db = DB_DataObject::factory('core_enum');
828 $db->query("show variables like 'innodb_file_per_table'");
830 if ($db->Value == 'OFF') {
831 die("Error: set innodb_file_per_table = 1 in my.cnf\n\n");
845 /** ------------- schema fixing ... there is an issue with data imported having the wrong sequence names... --- */
847 function fixSequencesMysql()
852 function fixSequencesPgsql()
856 //DB_DataObject::debugLevel(1);
857 $cs = DB_DataObject::factory('core_enum');
861 CASE WHEN strpos(seq_name, '.') > 0 THEN
864 quote_ident(min(schema_name)) ||'.'|| quote_ident(min(seq_name))
867 ||' OWNED BY '|| quote_ident(min(schema_name)) || '.' ||
868 quote_ident(min(table_name)) ||'.'|| quote_ident(min(column_name)) ||';' as cmd
872 n.nspname AS schema_name,
873 c.relname AS table_name,
874 a.attname AS column_name,
875 regexp_replace(regexp_replace(d.adsrc, E'nextval\\\\(+[''\\\"]*', ''),E'[''\\\"]*::.*\$','') AS seq_name
877 JOIN pg_attribute a ON (c.oid=a.attrelid)
878 JOIN pg_attrdef d ON (a.attrelid=d.adrelid AND a.attnum=d.adnum)
879 JOIN pg_namespace n ON (c.relnamespace=n.oid)
880 WHERE has_schema_privilege(n.oid,'USAGE')
881 AND n.nspname NOT LIKE 'pg!_%' escape '!'
882 AND has_table_privilege(c.oid,'SELECT')
883 AND (NOT a.attisdropped)
884 AND d.adsrc ~ '^nextval'
888 CASE WHEN strpos(seq_name, '.') > 0 THEN
889 substring(seq_name, 1,strpos(seq_name,'.')-1)
894 GROUP BY seq_name HAVING count(*)=1
897 while ($cs->fetch()) {
900 foreach($cmds as $cmd) {
901 $cs = DB_DataObject::factory('core_enum');
905 $cs = DB_DataObject::factory('core_enum');
907 SELECT 'SELECT SETVAL(' ||
908 quote_literal(quote_ident(nspname) || '.' || quote_ident(S.relname)) ||
909 ', MAX(' || quote_ident(C.attname)|| ')::integer ) FROM ' || nspname || '.' || quote_ident(T.relname)|| ';' as cmd
915 WHERE S.relkind = 'S'
917 AND D.refobjid = T.oid
918 AND D.refobjid = C.attrelid
919 AND D.refobjsubid = C.attnum
920 AND NS.oid = T.relnamespace
924 while ($cs->fetch()) {
927 foreach($cmds as $cmd) {
928 $cs = DB_DataObject::factory('core_enum');
935 var $extensions = array(
940 function runExtensions()
943 $ff = HTML_Flexyframework::get();
945 $dburl = parse_url($ff->DB_DataObject['database']);
947 $dbtype = $dburl['scheme'];
949 foreach($this->extensions as $ext) {
951 $scls = ucfirst($dbtype). $ext;
952 $cls = __CLASS__ . '_'. $scls;
953 $fn = implode('/',explode('_', $cls)).'.php';
954 if (!file_exists(__DIR__.'/UpdateDatabase/'. $scls .'.php')) {
965 function checkSystem()
967 // most of these are from File_Convert...
969 // these are required - and have simple dependancies.
970 require_once 'System.php';
976 'rsvg-convert', //librsvg2-bin
982 // these are prefered - but may have complicated depenacies
987 'html2text', // not availabe in debian squeeze
988 'pdftocairo', //poppler-utils - not available in debian squeeze.
998 foreach($req as $r) {
999 if (!System::which($r)) {
1005 $this->jerr("Missing these programs - need installing\n" . implode("\n",$res));
1007 foreach($pref as $r) {
1008 if (!System::which($r)) {
1014 echo "WARNING: Missing these programs - they may need installing\n". implode("\n",$res);