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();
198 if(in_array($m, $this->disabled)){
199 echo "module $m is disabled \n";
203 echo "Importing SQL from module $m\n";
204 if (!empty($this->opts['only-module-sql']) && $m != $this->opts['only-module-sql']) {
209 // check to see if the class has
213 $file = $this->rootDir. "/Pman/$m/UpdateDatabase.php";
214 if($m != 'Core' && file_exists($file)){
217 $class = "Pman_{$m}_UpdateDatabase";
219 if(method_exists($x, 'importModuleSQL')){
220 echo "Importing SQL from module $m using Module::importModuleSQL\n";
221 $x->opts = $this->opts;
222 $x->rootDir = $this->rootDir;
223 $x->importModuleSQL($dburl);
228 echo "Importing SQL from module $m\n";
231 // if init has been called
233 if (!empty($this->opts['init'])) {
234 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}.init");
240 $fd = $this->rootDir. "/Pman/$m/DataObjects";
242 $this->{$dirmethod}($dburl, $fd);
245 // new -- sql directory..
246 // new style will not support migrate ... they have to go into mysql-migrate.... directories..
247 // new style will not support pg.sql etc.. naming - that's what the direcotries are for..
249 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/sql");
250 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}");
254 if (!empty($this->opts['init']) && file_exists($this->rootDir. "/Pman/$m/{$dbtype}.initdata")) {
255 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
257 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}.initdata");
258 $this->{'fixSequences'. $dbtype}();
270 /** -------------- code to handle importing a whole directory of files into the database ------- **/
273 function importpgsqldir($url, $dir, $disable_triggers = false)
275 $ff = HTML_FlexyFramework::get();
277 require_once 'System.php';
278 $cat = System::which('cat');
279 $psql = System::which('psql');
282 if (!empty($url['pass'])) {
283 putenv("PGPASSWORD=". $url['pass']);
287 ' -h ' . $url['host'] .
288 ' -U' . escapeshellarg($url['user']) .
289 ' ' . basename($url['path']);
292 echo $psql_cmd . "\n" ;
293 echo "scan : $dir\n";
296 $files = array($dir);
301 $files = glob($dir.'/*.sql');
302 uksort($files, 'strcasecmp');
304 //$lsort = create_function('$a,$b','return strlen($a) > strlen($b) ? 1 : -1;');
305 //usort($files, $lsort);
308 foreach($files as $bfn) {
311 if (preg_match('/migrate/i', basename($bfn))) { // skip migration scripts at present..
314 if (preg_match('#\.[a-z]{2}\.sql#i', basename($bfn))
315 && !preg_match('#\.pg\.sql#i', basename($bfn))
316 ) { // skip migration scripts at present..
321 if (!preg_match('/pgsql/', basename($dir) )) {
322 if ( !preg_match('#\.pg\.sql$#', basename($bfn))) {
323 $fn = $this->convertToPG($bfn);
327 // files ending in .pg.sql are native postgres files.. ## depricated
330 $cmd = "$psql_cmd < " . escapeshellarg($fn ? $fn : $bfn) . ' 2>&1' ;
332 echo "$bfn: $cmd ". ($ff->cli ? "\n" : "<BR>\n");
348 * mysql - does not support conversions.
354 function importmysqldir($dburl, $dir)
357 $this->fixMysqlInnodb(); /// run once
359 echo "Import MYSQL :: $dir\n";
362 require_once 'System.php';
363 $cat = System::which('cat');
364 $mysql = System::which('mysql');
368 $mysql_cmd = $mysql .
369 ' -h ' . $dburl['host'] .
370 ' -u' . escapeshellarg($dburl['user']) .
371 (!empty($dburl['pass']) ? ' -p' . escapeshellarg($dburl['pass']) : '') .
372 ' ' . basename($dburl['path']);
373 //echo $mysql_cmd . "\n" ;
375 $files = glob($dir.'/*.sql');
376 uksort($files, 'strcasecmp');
379 foreach($files as $fn) {
382 if (preg_match('/migrate/i', basename($fn))) { // skip migration scripts at present..
385 // .my.sql but not .pg.sql
386 if (preg_match('#\.[a-z]{2}\.sql#i', basename($fn))
387 && !preg_match('#\.my\.sql#i', basename($fn))
388 ) { // skip migration scripts at present..
391 if (!strlen(trim($fn))) {
395 $cmd = "$mysql_cmd -f < " . escapeshellarg($fn) ." 2>&1" ;
397 echo basename($dir).'/'. basename($fn) . '::' . $cmd. ($this->cli ? "\n" : "<BR>\n");
400 $fp = popen($cmd, "r");
403 // send the current file part to the browser
404 $line = trim(fgets($fp, 1024));
409 if (!preg_match('/^ERROR\s+([0-9]+)/', $line, $matches)) {
410 echo " ---- {$line}\n"; flush();
414 switch($matches[1]) {
415 case 1017: // cause by renaming table -- old one does not exist..
416 case 1050: // create tables triggers this..
417 case 1060: // Duplicate column name
418 case 1061: // Duplicate key name - triggered by add index.. but could hide error. - unlikely though.
419 case 1091: // drop index -- name does not exist.. might hide errors..
421 case 1146: // drop a index on an unknown table.. - happens rarely...
422 case 1054: // Unknown column -- triggered by CHANGE COLUMN - but may hide other errrors..
428 echo " ---- {$line}\n"; flush();
432 // 1051: // Unknown table -- normally drop = add iff exists..
433 echo "File: $fn\n$line\n";
449 * simple regex based convert mysql to pgsql...
451 function convertToPG($src)
453 //echo "Convert $src\n";
455 $fn = $this->tempName('sql');
457 $ret = array( ); // pad it a bit.
458 $extra = array("", "" );
461 foreach(file($src) as $l) {
464 if (!strlen($l) || $l[0] == '#') {
468 if (preg_match('#create\s+table\s+([a-z0-9_]+)#i', $l, $m)) {
471 if (preg_match('#create\s+table\s+\`([a-z0-9_]+)\`#i', $l, $m)) {
472 $tbl = 'shop_' . strtolower($m[1]);
473 $l = preg_replace('#create\s+table\s+\`([a-z0-9_]+)\`#i', "CREATE TABLE {$tbl}", $l);
475 if (preg_match('#\`([a-z0-9_]+)\`#i', $l, $m) && !preg_match('#alter\s+table\s+#i', $l)) {
476 $l = preg_replace('#\`([a-z0-9_]+)\`#i', "{$m[1]}_name", $l);
479 if ($tbl && preg_match('#auto_increment#i', $l, $m)) {
480 $l = preg_replace('#auto_increment#i', "default nextval('{$tbl}_seq')", $l);
481 $extra[] = "create sequence {$tbl}_seq;";
485 if (preg_match('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', $l, $m)){
486 $l = preg_replace('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', "ALTER TABLE {$tbl}", $l);
489 // enum value -- use the text instead..
491 if ($tbl && preg_match('#([\w]+)\s+(enum\([\w|\W]+\))#i', $l, $m)) {
492 $l = preg_replace('#enum\([\w|\W]+\)#i', "TEXT", $l);
494 // ignore the alter enum
495 if ($tbl && preg_match('#alter\s+table\s+([\w|\W]+)\s+enum\([\w|\W]+\)#i', $l, $m)) {
499 // UNIQUE KEY .. ignore
500 if ($tbl && preg_match('#UNIQUE KEY#i', $l, $m)) {
501 $last = array_pop($ret);
502 $ret[] = trim($last, ",");
506 if ($tbl && preg_match('#RENAME\s+TO#i', $l, $m)) {
510 if ($tbl && preg_match('#change\s+column#i', $l, $m)) {
514 // INDEX lookup ..ignore
515 if ($tbl && preg_match('#INDEX lookup+([\w|\W]+)#i', $l, $m)) {
516 $last = array_pop($ret);
517 $ret[] = trim($last, ",");
522 // CREATE INDEX ..ignore
523 if (preg_match('#alter\s+table\s+([a-z0-9_]+)\s+add\s+index\s+#i', $l, $m)) {
524 // $l = "CREATE INDEX {$m[1]}_{$m[2]} ON {$m[1]} {$m[3]}";
529 $l = preg_replace('#int\([0-9]+\)#i', 'INT', $l);
531 $l = preg_replace('# datetime#i', ' TIMESTAMP WITHOUT TIME ZONE', $l);
532 $l = preg_replace('# blob#i', ' TEXT', $l);
533 $l = preg_replace('# longtext#i', ' TEXT', $l);
534 $l = preg_replace('# tinyint#i', ' INT', $l);
540 $ret = array_merge($extra,$ret);
541 // echo implode("\n", $ret); exit;
543 file_put_contents($fn, implode("\n", $ret));
549 function checkOpts($opts)
553 foreach($opts as $o=>$v) {
554 if (!preg_match('/^json-/', $o) || empty($v)) {
557 if (!file_exists($v)) {
558 die("File does not exist : OPTION --{$o} = {$v} \n");
562 $modules = array_reverse($this->modulesList());
564 // move 'project' one to the end...
566 foreach ($modules as $module){
567 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
568 if($module == 'Core' || !file_exists($file)){
572 $class = "Pman_{$module}_UpdateDatabase";
574 if(!method_exists($x, 'checkOpts')){
577 $x->checkOpts($opts);
581 static function jsonImportFromArray($opts)
583 foreach($opts as $o=>$v) {
584 if (!preg_match('/^json-/', $o) || empty($v)) {
587 $type = str_replace('_', '-', substr($o,5));
589 $data= json_decode(file_get_contents($v),true);
590 $pg = HTML_FlexyFramework::get()->page;
591 DB_DataObject::factory($type)->importFromArray($pg ,$data,$opts);
601 function runUpdateModulesData()
603 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
605 if(!in_array('Core', $this->disabled)){
606 echo "Running jsonImportFromArray\n";
607 Pman_Core_UpdateDatabase::jsonImportFromArray($this->opts);
610 echo "Running updateData on modules\n";
616 $modules = array_reverse($this->modulesList());
618 // move 'project' one to the end...
620 foreach ($modules as $module){
621 if(in_array($module, $this->disabled)){
624 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
625 if($module == 'Core' || !file_exists($file)){
630 $class = "Pman_{$module}_UpdateDatabase";
632 if(!method_exists($x, 'updateData')){
642 function updateDataEnums()
645 $enum = DB_DataObject::Factory('core_enum');
646 //DB_DAtaObject::debugLevel(1);
651 'name' => 'COMPTYPE',
652 'display_name' => 'Company Types',
653 'is_system_enum' => 1,
657 'display_name' => 'Owner',
658 'seqid' => 999, // last...
659 'is_system_enum' => 1,
666 'name' => 'HtmlEditor.font-family',
667 'display_name' => 'HTML Editor font families',
668 'is_system_enum' => 1,
671 'name' => 'Helvetica,Arial,sans-serif',
672 'display_name' => 'Helvetica',
677 'name' => 'Courier New',
678 'display_name' => 'Courier',
683 'display_name' => 'Tahoma',
687 'name' => 'Times New Roman,serif',
688 'display_name' => 'Times',
693 'display_name' => 'Verdana',
705 function updateDataGroups()
708 $groups = DB_DataObject::factory('groups');
709 $groups->initGroups();
711 $groups->initDatabase($this,array(
713 'name' => 'bcc-email', // group who are bcc'ed on all requests.
714 'type' => 0, // system
717 'name' => 'system-email-from',
718 'type' => 0, // system
721 'name' => 'core-person-signup-bcc',
722 'type' => 0, // system
728 function updateDataCompanies()
731 // fix comptypes enums..
732 $c = DB_DataObject::Factory('Companies');
734 $c->selectAdd('distinct(comptype) as comptype');
735 $c->whereAdd("comptype != ''");
738 foreach($c->fetchAll('comptype') as $cts) {
742 $ctb[]= array( 'etype'=>'COMPTYPE', 'name' => $cts, 'display_name' => ucfirst(strtolower($cts)));
745 $c = DB_DataObject::Factory('core_enum');
748 //DB_DataObject::debugLevel(1);
750 $c = DB_DataObject::Factory('Companies');
754 comptype_id = (SELECT id FROM core_enum where etype='comptype' and name=Companies.comptype LIMIT 1)
768 function initEmails($templateDir, $emails)
771 $pg = HTML_FlexyFramework::get()->page;
772 foreach($emails as $name=>$data) {
773 $cm = DB_DataObject::factory('core_email');
774 $update = $cm->get('name', $name);
777 if (empty($cm->bcc_group)) {
778 if (empty($data['bcc_group'])) {
779 $this->jerr("missing bcc_group for template $name");
781 $g = DB_DataObject::Factory('Groups')->lookup('name',$data['bcc_group']);
784 $this->jerr("bcc_group {$data['bcc_group']} does not exist when importing template $name");
786 if (!$g->members('email')) {
787 $this->jerr("bcc_group {$data['bcc_group']} does not have any members");
791 $cm->bcc_group = $g->id;
793 if (empty($cm->test_class)) {
794 if (empty($data['test_class'])) {
795 $this->jerr("missing test_class for template $name");
797 $cm->test_class = $data['test_class'];
799 require_once $cm->test_class . '.php';
801 $clsname = str_replace('/','_', $cm->test_class);
803 $method = new ReflectionMethod($clsname , 'test_'. $name) ;
804 $got_it = $method->isStatic();
805 } catch(Exception $e) {
810 $this->jerr("template {$name} does not have a test method {$clsname}::test_{$name}");
814 echo "email: {$name} - checked\n";
815 continue; /// we do not import the body content of templates that exist...
821 // $basedir = $this->bootLoader->rootDir . $mail_template_dir;
825 'file' => $templateDir. $name .'.html'
828 if (!empty($data['master'])) {
829 $opts['master'] = $templateDir . $master .'.html';
831 require_once 'Pman/Core/Import/Core_email.php';
832 $x = new Pman_Core_Import_Core_email();
835 echo "email: {$name} - CREATED\n";
840 function updateData()
843 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
844 $this->updateDataEnums();
845 $this->updateDataGroups();
846 $this->updateDataCompanies();
848 $c = DB_DataObject::Factory('I18n');
856 function fixMysqlInnodb()
859 static $done_check = false;
863 // innodb in single files is far more efficient that MYD or one big innodb file.
864 // first check if database is using this format.
865 $db = DB_DataObject::factory('core_enum');
866 $db->query("show variables like 'innodb_file_per_table'");
868 if ($db->Value == 'OFF') {
869 die("Error: set innodb_file_per_table = 1 in my.cnf\n\n");
883 /** ------------- schema fixing ... there is an issue with data imported having the wrong sequence names... --- */
885 function fixSequencesMysql()
890 function fixSequencesPgsql()
894 //DB_DataObject::debugLevel(1);
895 $cs = DB_DataObject::factory('core_enum');
899 CASE WHEN strpos(seq_name, '.') > 0 THEN
902 quote_ident(min(schema_name)) ||'.'|| quote_ident(min(seq_name))
905 ||' OWNED BY '|| quote_ident(min(schema_name)) || '.' ||
906 quote_ident(min(table_name)) ||'.'|| quote_ident(min(column_name)) ||';' as cmd
910 n.nspname AS schema_name,
911 c.relname AS table_name,
912 a.attname AS column_name,
913 regexp_replace(regexp_replace(d.adsrc, E'nextval\\\\(+[''\\\"]*', ''),E'[''\\\"]*::.*\$','') AS seq_name
915 JOIN pg_attribute a ON (c.oid=a.attrelid)
916 JOIN pg_attrdef d ON (a.attrelid=d.adrelid AND a.attnum=d.adnum)
917 JOIN pg_namespace n ON (c.relnamespace=n.oid)
918 WHERE has_schema_privilege(n.oid,'USAGE')
919 AND n.nspname NOT LIKE 'pg!_%' escape '!'
920 AND has_table_privilege(c.oid,'SELECT')
921 AND (NOT a.attisdropped)
922 AND d.adsrc ~ '^nextval'
926 CASE WHEN strpos(seq_name, '.') > 0 THEN
927 substring(seq_name, 1,strpos(seq_name,'.')-1)
932 GROUP BY seq_name HAVING count(*)=1
935 while ($cs->fetch()) {
938 foreach($cmds as $cmd) {
939 $cs = DB_DataObject::factory('core_enum');
943 $cs = DB_DataObject::factory('core_enum');
945 SELECT 'SELECT SETVAL(' ||
946 quote_literal(quote_ident(nspname) || '.' || quote_ident(S.relname)) ||
947 ', MAX(' || quote_ident(C.attname)|| ')::integer ) FROM ' || nspname || '.' || quote_ident(T.relname)|| ';' as cmd
953 WHERE S.relkind = 'S'
955 AND D.refobjid = T.oid
956 AND D.refobjid = C.attrelid
957 AND D.refobjsubid = C.attnum
958 AND NS.oid = T.relnamespace
962 while ($cs->fetch()) {
965 foreach($cmds as $cmd) {
966 $cs = DB_DataObject::factory('core_enum');
973 var $extensions = array(
978 function runExtensions()
981 $ff = HTML_Flexyframework::get();
983 $dburl = parse_url($ff->DB_DataObject['database']);
985 $dbtype = $dburl['scheme'];
987 foreach($this->extensions as $ext) {
989 $scls = ucfirst($dbtype). $ext;
990 $cls = __CLASS__ . '_'. $scls;
991 $fn = implode('/',explode('_', $cls)).'.php';
992 if (!file_exists(__DIR__.'/UpdateDatabase/'. $scls .'.php')) {
1003 function checkSystem()
1005 // most of these are from File_Convert...
1007 // these are required - and have simple dependancies.
1008 require_once 'System.php';
1014 'rsvg-convert', //librsvg2-bin
1020 // these are prefered - but may have complicated depenacies
1025 'html2text', // not availabe in debian squeeze
1026 'pdftocairo', //poppler-utils - not available in debian squeeze.
1036 foreach($req as $r) {
1037 if (!System::which($r)) {
1043 $this->jerr("Missing these programs - need installing\n" . implode("\n",$res));
1045 foreach($pref as $r) {
1046 if (!System::which($r)) {
1052 echo "WARNING: Missing these programs - they may need installing\n". implode("\n",$res);