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 $this->disabled = explode(',', $ff->disable);
140 //$this->fixSequencesPgsql();exit;
143 // ask all the modules to verify the opts
145 $this->checkOpts($opts);
147 if (empty($opts['data-only'])) {
150 if (!empty($opts['only-module-sql'])) {
154 $this->runUpdateModulesData();
157 if (!empty($opts['add-company']) && !in_array('Core', $this->disabled)) {
158 // make sure we have a good cache...?
160 DB_DataObject::factory('companies')->initCompanies($this, $opts);
163 $this->runExtensions();
171 * imports SQL files from all DataObjects directories....
173 * except any matching /migrate/
178 // loop through all the modules, and see if they have a importSQL method?
181 $ff = HTML_Flexyframework::get();
183 $dburl = parse_url($ff->DB_DataObject['database']);
185 //$this->{'import' . $url['scheme']}($url);
187 $dbtype = $dburl['scheme'];
188 $dirmethod = 'import' . $dburl['scheme'] . 'dir';
193 $ar = $this->modulesList();
197 if(in_array($m, $this->disabled)){
198 echo "module $m is disabled \n";
202 echo "Importing SQL from module $m\n";
203 if (!empty($this->opts['only-module-sql']) && $m != $this->opts['only-module-sql']) {
208 // check to see if the class has
212 $file = $this->rootDir. "/Pman/$m/UpdateDatabase.php";
213 if($m != 'Core' && file_exists($file)){
216 $class = "Pman_{$m}_UpdateDatabase";
218 if(method_exists($x, 'importModuleSQL')){
219 echo "Importing SQL from module $m using Module::importModuleSQL\n";
220 $x->opts = $this->opts;
221 $x->rootDir = $this->rootDir;
222 $x->importModuleSQL($dburl);
227 echo "Importing SQL from module $m\n";
230 // if init has been called
232 if (!empty($this->opts['init'])) {
233 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}.init");
239 $fd = $this->rootDir. "/Pman/$m/DataObjects";
241 $this->{$dirmethod}($dburl, $fd);
244 // new -- sql directory..
245 // new style will not support migrate ... they have to go into mysql-migrate.... directories..
246 // new style will not support pg.sql etc.. naming - that's what the direcotries are for..
248 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/sql");
249 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}");
253 if (!empty($this->opts['init']) && file_exists($this->rootDir. "/Pman/$m/{$dbtype}.initdata")) {
254 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
256 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}.initdata");
257 $this->{'fixSequences'. $dbtype}();
269 /** -------------- code to handle importing a whole directory of files into the database ------- **/
272 function importpgsqldir($url, $dir, $disable_triggers = false)
274 $ff = HTML_FlexyFramework::get();
276 require_once 'System.php';
277 $cat = System::which('cat');
278 $psql = System::which('psql');
281 if (!empty($url['pass'])) {
282 putenv("PGPASSWORD=". $url['pass']);
286 ' -h ' . $url['host'] .
287 ' -U' . escapeshellarg($url['user']) .
288 ' ' . basename($url['path']);
291 echo $psql_cmd . "\n" ;
292 echo "scan : $dir\n";
295 $files = array($dir);
300 $files = glob($dir.'/*.sql');
301 uksort($files, 'strcasecmp');
303 //$lsort = create_function('$a,$b','return strlen($a) > strlen($b) ? 1 : -1;');
304 //usort($files, $lsort);
307 foreach($files as $bfn) {
310 if (preg_match('/migrate/i', basename($bfn))) { // skip migration scripts at present..
313 if (preg_match('#\.[a-z]{2}\.sql#i', basename($bfn))
314 && !preg_match('#\.pg\.sql#i', basename($bfn))
315 ) { // skip migration scripts at present..
320 if (!preg_match('/pgsql/', basename($dir) )) {
321 if ( !preg_match('#\.pg\.sql$#', basename($bfn))) {
322 $fn = $this->convertToPG($bfn);
326 // files ending in .pg.sql are native postgres files.. ## depricated
329 $cmd = "$psql_cmd < " . escapeshellarg($fn ? $fn : $bfn) . ' 2>&1' ;
331 echo "$bfn: $cmd ". ($ff->cli ? "\n" : "<BR>\n");
347 * mysql - does not support conversions.
353 function importmysqldir($dburl, $dir)
356 $this->fixMysqlInnodb(); /// run once
358 echo "Import MYSQL :: $dir\n";
361 require_once 'System.php';
362 $cat = System::which('cat');
363 $mysql = System::which('mysql');
367 $mysql_cmd = $mysql .
368 ' -h ' . $dburl['host'] .
369 ' -u' . escapeshellarg($dburl['user']) .
370 (!empty($dburl['pass']) ? ' -p' . escapeshellarg($dburl['pass']) : '') .
371 ' ' . basename($dburl['path']);
372 //echo $mysql_cmd . "\n" ;
374 $files = glob($dir.'/*.sql');
375 uksort($files, 'strcasecmp');
378 foreach($files as $fn) {
381 if (preg_match('/migrate/i', basename($fn))) { // skip migration scripts at present..
384 // .my.sql but not .pg.sql
385 if (preg_match('#\.[a-z]{2}\.sql#i', basename($fn))
386 && !preg_match('#\.my\.sql#i', basename($fn))
387 ) { // skip migration scripts at present..
390 if (!strlen(trim($fn))) {
394 $cmd = "$mysql_cmd -f < " . escapeshellarg($fn) ;
396 echo basename($dir).'/'. basename($fn) . '::' . $cmd. ($this->cli ? "\n" : "<BR>\n");
409 * simple regex based convert mysql to pgsql...
411 function convertToPG($src)
413 //echo "Convert $src\n";
415 $fn = $this->tempName('sql');
417 $ret = array( ); // pad it a bit.
418 $extra = array("", "" );
421 foreach(file($src) as $l) {
424 if (!strlen($l) || $l[0] == '#') {
428 if (preg_match('#create\s+table\s+([a-z0-9_]+)#i', $l, $m)) {
431 if (preg_match('#create\s+table\s+\`([a-z0-9_]+)\`#i', $l, $m)) {
432 $tbl = 'shop_' . strtolower($m[1]);
433 $l = preg_replace('#create\s+table\s+\`([a-z0-9_]+)\`#i', "CREATE TABLE {$tbl}", $l);
435 if (preg_match('#\`([a-z0-9_]+)\`#i', $l, $m) && !preg_match('#alter\s+table\s+#i', $l)) {
436 $l = preg_replace('#\`([a-z0-9_]+)\`#i', "{$m[1]}_name", $l);
439 if ($tbl && preg_match('#auto_increment#i', $l, $m)) {
440 $l = preg_replace('#auto_increment#i', "default nextval('{$tbl}_seq')", $l);
441 $extra[] = "create sequence {$tbl}_seq;";
445 if (preg_match('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', $l, $m)){
446 $l = preg_replace('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', "ALTER TABLE {$tbl}", $l);
449 // enum value -- use the text instead..
451 if ($tbl && preg_match('#([\w]+)\s+(enum\([\w|\W]+\))#i', $l, $m)) {
452 $l = preg_replace('#enum\([\w|\W]+\)#i', "TEXT", $l);
454 // ignore the alter enum
455 if ($tbl && preg_match('#alter\s+table\s+([\w|\W]+)\s+enum\([\w|\W]+\)#i', $l, $m)) {
459 // UNIQUE KEY .. ignore
460 if ($tbl && preg_match('#UNIQUE KEY#i', $l, $m)) {
461 $last = array_pop($ret);
462 $ret[] = trim($last, ",");
466 if ($tbl && preg_match('#RENAME\s+TO#i', $l, $m)) {
470 if ($tbl && preg_match('#change\s+column#i', $l, $m)) {
474 // INDEX lookup ..ignore
475 if ($tbl && preg_match('#INDEX lookup+([\w|\W]+)#i', $l, $m)) {
476 $last = array_pop($ret);
477 $ret[] = trim($last, ",");
482 // CREATE INDEX ..ignore
483 if (preg_match('#alter\s+table\s+([a-z0-9_]+)\s+add\s+index\s+#i', $l, $m)) {
484 // $l = "CREATE INDEX {$m[1]}_{$m[2]} ON {$m[1]} {$m[3]}";
489 $l = preg_replace('#int\([0-9]+\)#i', 'INT', $l);
491 $l = preg_replace('# datetime#i', ' TIMESTAMP WITHOUT TIME ZONE', $l);
492 $l = preg_replace('# blob#i', ' TEXT', $l);
493 $l = preg_replace('# longtext#i', ' TEXT', $l);
494 $l = preg_replace('# tinyint#i', ' INT', $l);
500 $ret = array_merge($extra,$ret);
501 // echo implode("\n", $ret); exit;
503 file_put_contents($fn, implode("\n", $ret));
509 function checkOpts($opts)
513 foreach($opts as $o=>$v) {
514 if (!preg_match('/^json-/', $o) || empty($v)) {
517 if (!file_exists($v)) {
518 die("File does not exist : OPTION --{$o} = {$v} \n");
522 $modules = array_reverse($this->modulesList());
524 // move 'project' one to the end...
526 foreach ($modules as $module){
527 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
528 if($module == 'Core' || !file_exists($file)){
532 $class = "Pman_{$module}_UpdateDatabase";
534 if(!method_exists($x, 'checkOpts')){
537 $x->checkOpts($opts);
541 static function jsonImportFromArray($opts)
543 foreach($opts as $o=>$v) {
544 if (!preg_match('/^json-/', $o) || empty($v)) {
547 $type = str_replace('_', '-', substr($o,5));
549 $data= json_decode(file_get_contents($v),true);
550 $pg = HTML_FlexyFramework::get()->page;
551 DB_DataObject::factory($type)->importFromArray($pg ,$data,$opts);
561 function runUpdateModulesData()
563 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
565 if(!in_array('Core', $this->disabled)){
566 echo "Running jsonImportFromArray\n";
567 Pman_Core_UpdateDatabase::jsonImportFromArray($this->opts);
570 echo "Running updateData on modules\n";
576 $modules = array_reverse($this->modulesList());
578 // move 'project' one to the end...
580 foreach ($modules as $module){
581 if(in_array($module, $this->disabled)){
584 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
585 if($module == 'Core' || !file_exists($file)){
590 $class = "Pman_{$module}_UpdateDatabase";
592 if(!method_exists($x, 'updateData')){
602 function updateDataEnums()
605 $enum = DB_DataObject::Factory('core_enum');
606 //DB_DAtaObject::debugLevel(1);
611 'name' => 'COMPTYPE',
612 'display_name' => 'Company Types',
613 'is_system_enum' => 1,
617 'display_name' => 'Owner',
618 'seqid' => 999, // last...
619 'is_system_enum' => 1,
626 'name' => 'HtmlEditor.font-family',
627 'display_name' => 'HTML Editor font families',
628 'is_system_enum' => 1,
631 'name' => 'Helvetica,Arial,sans-serif',
632 'display_name' => 'Helvetica',
637 'name' => 'Courier New',
638 'display_name' => 'Courier',
643 'display_name' => 'Tahoma',
647 'name' => 'Times New Roman,serif',
648 'display_name' => 'Times',
653 'display_name' => 'Verdana',
665 function updateDataGroups()
668 $groups = DB_DataObject::factory('groups');
669 $groups->initGroups();
671 $groups->initDatabase($this,array(
673 'name' => 'bcc-email', // group who are bcc'ed on all requests.
674 'type' => 0, // system
677 'name' => 'system-email-from',
678 'type' => 0, // system
681 'name' => 'core-person-signup-bcc',
682 'type' => 0, // system
688 function updateDataCompanies()
691 // fix comptypes enums..
692 $c = DB_DataObject::Factory('Companies');
694 $c->selectAdd('distinct(comptype) as comptype');
695 $c->whereAdd("comptype != ''");
698 foreach($c->fetchAll('comptype') as $cts) {
702 $ctb[]= array( 'etype'=>'COMPTYPE', 'name' => $cts, 'display_name' => ucfirst(strtolower($cts)));
705 $c = DB_DataObject::Factory('core_enum');
708 //DB_DataObject::debugLevel(1);
710 $c = DB_DataObject::Factory('Companies');
714 comptype_id = (SELECT id FROM core_enum where etype='comptype' and name=Companies.comptype LIMIT 1)
728 function initEmails($templateDir, $emails)
731 $pg = HTML_FlexyFramework::get()->page;
732 foreach($emails as $name=>$data) {
733 $cm = DB_DataObject::factory('core_email');
734 $update = $cm->get('name', $name);
737 if (empty($cm->bcc_group)) {
738 if (empty($data['bcc_group'])) {
739 $this->jerr("missing bcc_group for template $name");
741 $g = DB_DataObject::Factory('Groups')->lookup('name',$data['bcc_group']);
744 $this->jerr("bcc_group {$data['bcc_group']} does not exist when importing template $name");
746 if (!$g->members('email')) {
747 $this->jerr("bcc_group {$data['bcc_group']} does not have any members");
751 $cm->bcc_group = $g->id;
753 if (empty($cm->test_class)) {
754 if (empty($data['test_class'])) {
755 $this->jerr("missing test_class for template $name");
757 $cm->test_class = $data['test_class'];
759 require_once $cm->test_class . '.php';
761 $clsname = str_replace('/','_', $cm->test_class);
763 $method = new ReflectionMethod($clsname , 'test_'. $name) ;
764 $got_it = $method->isStatic();
765 } catch(Exception $e) {
770 $this->jerr("template {$name} does not have a test method {$clsname}::test_{$name}");
774 echo "email: {$name} - checked\n";
775 continue; /// we do not import the body content of templates that exist...
781 // $basedir = $this->bootLoader->rootDir . $mail_template_dir;
785 'file' => $templateDir. $name .'.html'
788 if (!empty($data['master'])) {
789 $opts['master'] = $templateDir . $master .'.html';
791 require_once 'Pman/Core/Import/Core_email.php';
792 $x = new Pman_Core_Import_Core_email();
795 echo "email: {$name} - CREATED\n";
800 function updateData()
803 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
804 $this->updateDataEnums();
805 $this->updateDataGroups();
806 $this->updateDataCompanies();
808 $c = DB_DataObject::Factory('I18n');
816 function fixMysqlInnodb()
819 static $done_check = false;
823 // innodb in single files is far more efficient that MYD or one big innodb file.
824 // first check if database is using this format.
825 $db = DB_DataObject::factory('core_enum');
826 $db->query("show variables like 'innodb_file_per_table'");
828 if ($db->Value == 'OFF') {
829 die("Error: set innodb_file_per_table = 1 in my.cnf\n\n");
843 /** ------------- schema fixing ... there is an issue with data imported having the wrong sequence names... --- */
845 function fixSequencesMysql()
850 function fixSequencesPgsql()
854 //DB_DataObject::debugLevel(1);
855 $cs = DB_DataObject::factory('core_enum');
859 CASE WHEN strpos(seq_name, '.') > 0 THEN
862 quote_ident(min(schema_name)) ||'.'|| quote_ident(min(seq_name))
865 ||' OWNED BY '|| quote_ident(min(schema_name)) || '.' ||
866 quote_ident(min(table_name)) ||'.'|| quote_ident(min(column_name)) ||';' as cmd
870 n.nspname AS schema_name,
871 c.relname AS table_name,
872 a.attname AS column_name,
873 regexp_replace(regexp_replace(d.adsrc, E'nextval\\\\(+[''\\\"]*', ''),E'[''\\\"]*::.*\$','') AS seq_name
875 JOIN pg_attribute a ON (c.oid=a.attrelid)
876 JOIN pg_attrdef d ON (a.attrelid=d.adrelid AND a.attnum=d.adnum)
877 JOIN pg_namespace n ON (c.relnamespace=n.oid)
878 WHERE has_schema_privilege(n.oid,'USAGE')
879 AND n.nspname NOT LIKE 'pg!_%' escape '!'
880 AND has_table_privilege(c.oid,'SELECT')
881 AND (NOT a.attisdropped)
882 AND d.adsrc ~ '^nextval'
886 CASE WHEN strpos(seq_name, '.') > 0 THEN
887 substring(seq_name, 1,strpos(seq_name,'.')-1)
892 GROUP BY seq_name HAVING count(*)=1
895 while ($cs->fetch()) {
898 foreach($cmds as $cmd) {
899 $cs = DB_DataObject::factory('core_enum');
903 $cs = DB_DataObject::factory('core_enum');
905 SELECT 'SELECT SETVAL(' ||
906 quote_literal(quote_ident(nspname) || '.' || quote_ident(S.relname)) ||
907 ', MAX(' || quote_ident(C.attname)|| ')::integer ) FROM ' || nspname || '.' || quote_ident(T.relname)|| ';' as cmd
913 WHERE S.relkind = 'S'
915 AND D.refobjid = T.oid
916 AND D.refobjid = C.attrelid
917 AND D.refobjsubid = C.attnum
918 AND NS.oid = T.relnamespace
922 while ($cs->fetch()) {
925 foreach($cmds as $cmd) {
926 $cs = DB_DataObject::factory('core_enum');
933 var $extensions = array(
938 function runExtensions()
941 $ff = HTML_Flexyframework::get();
943 $dburl = parse_url($ff->DB_DataObject['database']);
945 $dbtype = $dburl['scheme'];
947 foreach($this->extensions as $ext) {
949 $scls = ucfirst($dbtype). $ext;
950 $cls = __CLASS__ . '_'. $scls;
951 $fn = implode('/',explode('_', $cls)).'.php';
952 if (!file_exists(__DIR__.'/UpdateDatabase/'. $scls .'.php')) {
963 function checkSystem()
965 // most of these are from File_Convert...
967 // these are required - and have simple dependancies.
968 require_once 'System.php';
974 'rsvg-convert', //librsvg2-bin
980 // these are prefered - but may have complicated depenacies
985 'html2text', // not availabe in debian squeeze
986 'pdftocairo', //poppler-utils - not available in debian squeeze.
996 foreach($req as $r) {
997 if (!System::which($r)) {
1003 $this->jerr("Missing these programs - need installing\n" . implode("\n",$res));
1005 foreach($pref as $r) {
1006 if (!System::which($r)) {
1012 echo "WARNING: Missing these programs - they may need installing\n". implode("\n",$res);