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 $this->runExtensions(); // do this first, so the innodb change + utf8 fixes column max sizes
156 if (empty($opts['data-only'])) {
159 if (!empty($opts['only-module-sql'])) {
163 $this->runUpdateModulesData();
166 if (!empty($opts['add-company']) && !in_array('Core', $this->disabled)) {
167 // make sure we have a good cache...?
169 DB_DataObject::factory('companies')->initCompanies($this, $opts);
172 $this->runExtensions();
180 * imports SQL files from all DataObjects directories....
182 * except any matching /migrate/
187 // loop through all the modules, and see if they have a importSQL method?
190 $ff = HTML_Flexyframework::get();
192 $dburl = parse_url($ff->DB_DataObject['database']);
194 //$this->{'import' . $url['scheme']}($url);
196 $dbtype = $dburl['scheme'];
197 $dirmethod = 'import' . $dburl['scheme'] . 'dir';
202 $ar = $this->modulesList();
207 if(in_array($m, $this->disabled)){
208 echo "module $m is disabled \n";
212 echo "Importing SQL from module $m\n";
213 if (!empty($this->opts['only-module-sql']) && $m != $this->opts['only-module-sql']) {
218 // check to see if the class has
222 $file = $this->rootDir. "/Pman/$m/UpdateDatabase.php";
223 if($m != 'Core' && file_exists($file)){
226 $class = "Pman_{$m}_UpdateDatabase";
228 if(method_exists($x, 'importModuleSQL')){
229 echo "Importing SQL from module $m using Module::importModuleSQL\n";
230 $x->opts = $this->opts;
231 $x->rootDir = $this->rootDir;
232 $x->importModuleSQL($dburl);
237 echo "Importing SQL from module $m\n";
240 // if init has been called
242 if (!empty($this->opts['init'])) {
243 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}.init");
249 $fd = $this->rootDir. "/Pman/$m/DataObjects";
251 $this->{$dirmethod}($dburl, $fd);
254 // new -- sql directory..
255 // new style will not support migrate ... they have to go into mysql-migrate.... directories..
256 // new style will not support pg.sql etc.. naming - that's what the direcotries are for..
258 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/sql");
259 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}");
263 if (!empty($this->opts['init']) && file_exists($this->rootDir. "/Pman/$m/{$dbtype}.initdata")) {
264 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
266 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}.initdata");
267 $this->{'fixSequences'. $dbtype}();
279 /** -------------- code to handle importing a whole directory of files into the database ------- **/
282 function importpgsqldir($url, $dir, $disable_triggers = false)
284 $ff = HTML_FlexyFramework::get();
286 require_once 'System.php';
287 $cat = System::which('cat');
288 $psql = System::which('psql');
291 if (!empty($url['pass'])) {
292 putenv("PGPASSWORD=". $url['pass']);
296 ' -h ' . $url['host'] .
297 ' -U' . escapeshellarg($url['user']) .
298 ' ' . basename($url['path']);
301 echo $psql_cmd . "\n" ;
302 echo "scan : $dir\n";
305 $files = array($dir);
310 $files = glob($dir.'/*.sql');
311 uksort($files, 'strcasecmp');
313 //$lsort = create_function('$a,$b','return strlen($a) > strlen($b) ? 1 : -1;');
314 //usort($files, $lsort);
317 foreach($files as $bfn) {
320 if (preg_match('/migrate/i', basename($bfn))) { // skip migration scripts at present..
323 if (preg_match('#\.[a-z]{2}\.sql#i', basename($bfn))
324 && !preg_match('#\.pg\.sql#i', basename($bfn))
325 ) { // skip migration scripts at present..
330 if (!preg_match('/pgsql/', basename($dir) )) {
331 if ( !preg_match('#\.pg\.sql$#', basename($bfn))) {
332 $fn = $this->convertToPG($bfn);
336 // files ending in .pg.sql are native postgres files.. ## depricated
339 $cmd = "$psql_cmd < " . escapeshellarg($fn ? $fn : $bfn) . ' 2>&1' ;
341 echo "$bfn: $cmd ". ($ff->cli ? "\n" : "<BR>\n");
357 * mysql - does not support conversions.
363 function importmysqldir($dburl, $dir)
366 $this->fixMysqlInnodb(); /// run once
368 echo "Import MYSQL :: $dir\n";
371 require_once 'System.php';
372 $cat = System::which('cat');
373 $mysql = System::which('mysql');
377 $mysql_cmd = $mysql .
378 ' -h ' . $dburl['host'] .
379 ' -u' . escapeshellarg($dburl['user']) .
380 (!empty($dburl['pass']) ? ' -p' . escapeshellarg($dburl['pass']) : '') .
381 ' ' . basename($dburl['path']);
382 //echo $mysql_cmd . "\n" ;
384 $files = glob($dir.'/*.sql');
385 uksort($files, 'strcasecmp');
388 foreach($files as $fn) {
391 if (preg_match('/migrate/i', basename($fn))) { // skip migration scripts at present..
394 // .my.sql but not .pg.sql
395 if (preg_match('#\.[a-z]{2}\.sql#i', basename($fn))
396 && !preg_match('#\.my\.sql#i', basename($fn))
397 ) { // skip migration scripts at present..
400 if (!strlen(trim($fn))) {
404 $cmd = "$mysql_cmd -f < " . escapeshellarg($fn) ." 2>&1" ;
406 echo basename($dir).'/'. basename($fn) . '::' . $cmd. ($this->cli ? "\n" : "<BR>\n");
409 $fp = popen($cmd, "r");
412 // send the current file part to the browser
413 $line = trim(fgets($fp, 1024));
418 if (!preg_match('/^ERROR\s+([0-9]+)/', $line, $matches)) {
419 echo " ---- {$line}\n"; flush();
423 switch($matches[1]) {
424 case 1017: // cause by renaming table -- old one does not exist..
425 case 1050: // create tables triggers this..
426 case 1060: // Duplicate column name
427 case 1061: // Duplicate key name - triggered by add index.. but could hide error. - unlikely though.
428 case 1091: // drop index -- name does not exist.. might hide errors..
430 case 1146: // drop a index on an unknown table.. - happens rarely...
431 case 1054: // Unknown column -- triggered by CHANGE COLUMN - but may hide other errrors..
437 echo " ---- {$line}\n"; flush();
441 // 1051: // Unknown table -- normally drop = add iff exists..
442 echo "File: $fn\n$line\n";
458 * simple regex based convert mysql to pgsql...
460 function convertToPG($src)
462 //echo "Convert $src\n";
464 $fn = $this->tempName('sql');
466 $ret = array( ); // pad it a bit.
467 $extra = array("", "" );
470 foreach(file($src) as $l) {
473 if (!strlen($l) || $l[0] == '#') {
477 if (preg_match('#create\s+table\s+([a-z0-9_]+)#i', $l, $m)) {
480 if (preg_match('#create\s+table\s+\`([a-z0-9_]+)\`#i', $l, $m)) {
481 $tbl = 'shop_' . strtolower($m[1]);
482 $l = preg_replace('#create\s+table\s+\`([a-z0-9_]+)\`#i', "CREATE TABLE {$tbl}", $l);
484 if (preg_match('#\`([a-z0-9_]+)\`#i', $l, $m) && !preg_match('#alter\s+table\s+#i', $l)) {
485 $l = preg_replace('#\`([a-z0-9_]+)\`#i', "{$m[1]}_name", $l);
488 if ($tbl && preg_match('#auto_increment#i', $l, $m)) {
489 $l = preg_replace('#auto_increment#i', "default nextval('{$tbl}_seq')", $l);
490 $extra[] = "create sequence {$tbl}_seq;";
494 if (preg_match('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', $l, $m)){
495 $l = preg_replace('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', "ALTER TABLE {$tbl}", $l);
498 // enum value -- use the text instead..
500 if ($tbl && preg_match('#([\w]+)\s+(enum\([\w|\W]+\))#i', $l, $m)) {
501 $l = preg_replace('#enum\([\w|\W]+\)#i', "TEXT", $l);
503 // ignore the alter enum
504 if ($tbl && preg_match('#alter\s+table\s+([\w|\W]+)\s+enum\([\w|\W]+\)#i', $l, $m)) {
508 // UNIQUE KEY .. ignore
509 if ($tbl && preg_match('#UNIQUE KEY#i', $l, $m)) {
510 $last = array_pop($ret);
511 $ret[] = trim($last, ",");
515 if ($tbl && preg_match('#RENAME\s+TO#i', $l, $m)) {
519 if ($tbl && preg_match('#change\s+column#i', $l, $m)) {
523 // INDEX lookup ..ignore
524 if ($tbl && preg_match('#INDEX lookup+([\w|\W]+)#i', $l, $m)) {
525 $last = array_pop($ret);
526 $ret[] = trim($last, ",");
531 // CREATE INDEX ..ignore
532 if (preg_match('#alter\s+table\s+([a-z0-9_]+)\s+add\s+index\s+#i', $l, $m)) {
533 // $l = "CREATE INDEX {$m[1]}_{$m[2]} ON {$m[1]} {$m[3]}";
538 $l = preg_replace('#int\([0-9]+\)#i', 'INT', $l);
540 $l = preg_replace('# datetime#i', ' TIMESTAMP WITHOUT TIME ZONE', $l);
541 $l = preg_replace('# blob#i', ' TEXT', $l);
542 $l = preg_replace('# longtext#i', ' TEXT', $l);
543 $l = preg_replace('# tinyint#i', ' INT', $l);
549 $ret = array_merge($extra,$ret);
550 // echo implode("\n", $ret); exit;
552 file_put_contents($fn, implode("\n", $ret));
558 function checkOpts($opts)
562 foreach($opts as $o=>$v) {
563 if (!preg_match('/^json-/', $o) || empty($v)) {
566 if (!file_exists($v)) {
567 die("File does not exist : OPTION --{$o} = {$v} \n");
571 $modules = array_reverse($this->modulesList());
573 // move 'project' one to the end...
575 foreach ($modules as $module){
576 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
577 if($module == 'Core' || !file_exists($file)){
581 $class = "Pman_{$module}_UpdateDatabase";
583 if(!method_exists($x, 'checkOpts')){
586 $x->checkOpts($opts);
590 static function jsonImportFromArray($opts)
592 foreach($opts as $o=>$v) {
593 if (!preg_match('/^json-/', $o) || empty($v)) {
596 $type = str_replace('_', '-', substr($o,5));
598 $data= json_decode(file_get_contents($v),true);
599 $pg = HTML_FlexyFramework::get()->page;
600 DB_DataObject::factory($type)->importFromArray($pg ,$data,$opts);
610 function runUpdateModulesData()
612 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
614 if(!in_array('Core', $this->disabled)){
615 echo "Running jsonImportFromArray\n";
616 Pman_Core_UpdateDatabase::jsonImportFromArray($this->opts);
619 echo "Running updateData on modules\n";
625 $modules = array_reverse($this->modulesList());
627 // move 'project' one to the end...
629 foreach ($modules as $module){
630 if(in_array($module, $this->disabled)){
633 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
634 if($module == 'Core' || !file_exists($file)){
639 $class = "Pman_{$module}_UpdateDatabase";
641 if(!method_exists($x, 'updateData')){
651 function updateDataEnums()
654 $enum = DB_DataObject::Factory('core_enum');
655 //DB_DAtaObject::debugLevel(1);
660 'name' => 'COMPTYPE',
661 'display_name' => 'Company Types',
662 'is_system_enum' => 1,
666 'display_name' => 'Owner',
667 'seqid' => 999, // last...
668 'is_system_enum' => 1,
675 'name' => 'HtmlEditor.font-family',
676 'display_name' => 'HTML Editor font families',
677 'is_system_enum' => 1,
680 'name' => 'Helvetica,Arial,sans-serif',
681 'display_name' => 'Helvetica',
686 'name' => 'Courier New',
687 'display_name' => 'Courier',
692 'display_name' => 'Tahoma',
696 'name' => 'Times New Roman,serif',
697 'display_name' => 'Times',
702 'display_name' => 'Verdana',
714 function updateDataGroups()
717 $groups = DB_DataObject::factory('groups');
718 $groups->initGroups();
720 $groups->initDatabase($this,array(
722 'name' => 'bcc-email', // group who are bcc'ed on all requests.
723 'type' => 0, // system
726 'name' => 'system-email-from',
727 'type' => 0, // system
730 'name' => 'core-person-signup-bcc',
731 'type' => 0, // system
737 function updateDataCompanies()
740 // fix comptypes enums..
741 $c = DB_DataObject::Factory('Companies');
743 $c->selectAdd('distinct(comptype) as comptype');
744 $c->whereAdd("comptype != ''");
747 foreach($c->fetchAll('comptype') as $cts) {
751 $ctb[]= array( 'etype'=>'COMPTYPE', 'name' => $cts, 'display_name' => ucfirst(strtolower($cts)));
754 $c = DB_DataObject::Factory('core_enum');
757 //DB_DataObject::debugLevel(1);
759 $c = DB_DataObject::Factory('Companies');
763 comptype_id = (SELECT id FROM core_enum where etype='comptype' and name=Companies.comptype LIMIT 1)
777 function initEmails($templateDir, $emails)
780 $pg = HTML_FlexyFramework::get()->page;
781 foreach($emails as $name=>$data) {
782 $cm = DB_DataObject::factory('core_email');
783 $update = $cm->get('name', $name);
786 if (empty($cm->bcc_group)) {
787 if (empty($data['bcc_group'])) {
788 $this->jerr("missing bcc_group for template $name");
790 $g = DB_DataObject::Factory('Groups')->lookup('name',$data['bcc_group']);
793 $this->jerr("bcc_group {$data['bcc_group']} does not exist when importing template $name");
797 if (!$g->members('email')) {
798 $this->jerr("bcc_group {$data['bcc_group']} does not have any members");
801 $cm->bcc_group = $g->id;
803 if (empty($cm->test_class)) {
804 if (empty($data['test_class'])) {
805 $this->jerr("missing test_class for template $name");
807 $cm->test_class = $data['test_class'];
809 require_once $cm->test_class . '.php';
811 $clsname = str_replace('/','_', $cm->test_class);
813 $method = new ReflectionMethod($clsname , 'test_'. $name) ;
814 $got_it = $method->isStatic();
815 } catch(Exception $e) {
820 $this->jerr("template {$name} does not have a test method {$clsname}::test_{$name}");
824 echo "email: {$name} - checked\n";
825 continue; /// we do not import the body content of templates that exist...
832 // $basedir = $this->bootLoader->rootDir . $mail_template_dir;
836 'file' => $templateDir. $name .'.html'
839 if (!empty($data['master'])) {
840 $opts['master'] = $templateDir . $master .'.html';
842 require_once 'Pman/Core/Import/Core_email.php';
843 $x = new Pman_Core_Import_Core_email();
844 $x->updateOrCreateEmail('', $opts, $cm);
846 echo "email: {$name} - CREATED\n";
851 function updateData()
854 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
855 $this->updateDataEnums();
856 $this->updateDataGroups();
857 $this->updateDataCompanies();
859 $c = DB_DataObject::Factory('I18n');
867 function fixMysqlInnodb()
870 static $done_check = false;
874 // innodb in single files is far more efficient that MYD or one big innodb file.
875 // first check if database is using this format.
876 $db = DB_DataObject::factory('core_enum');
877 $db->query("show variables like 'innodb_file_per_table'");
879 if ($db->Value == 'OFF') {
880 die("Error: set innodb_file_per_table = 1 in my.cnf\n\n");
883 $db = DB_DataObject::factory('core_enum');
884 $db->query("show variables like 'sql_mode'");
887 $modes = explode(",", $db->Value);
890 in_array('NO_ZERO_IN_DATE', $modes) ||
891 in_array('NO_ZERO_DATE', $modes) ||
892 !in_array('ALLOW_INVALID_DATES', $modes)
894 die("Error: set sql_mode include 'ALLOW_INVALID_DATES', remove 'NO_ZERO_IN_DATE' AND 'NO_ZERO_DATE' in my.cnf\n\n");
908 /** ------------- schema fixing ... there is an issue with data imported having the wrong sequence names... --- */
910 function fixSequencesMysql()
915 function fixSequencesPgsql()
919 //DB_DataObject::debugLevel(1);
920 $cs = DB_DataObject::factory('core_enum');
924 CASE WHEN strpos(seq_name, '.') > 0 THEN
927 quote_ident(min(schema_name)) ||'.'|| quote_ident(min(seq_name))
930 ||' OWNED BY '|| quote_ident(min(schema_name)) || '.' ||
931 quote_ident(min(table_name)) ||'.'|| quote_ident(min(column_name)) ||';' as cmd
935 n.nspname AS schema_name,
936 c.relname AS table_name,
937 a.attname AS column_name,
938 regexp_replace(regexp_replace(d.adsrc, E'nextval\\\\(+[''\\\"]*', ''),E'[''\\\"]*::.*\$','') AS seq_name
940 JOIN pg_attribute a ON (c.oid=a.attrelid)
941 JOIN pg_attrdef d ON (a.attrelid=d.adrelid AND a.attnum=d.adnum)
942 JOIN pg_namespace n ON (c.relnamespace=n.oid)
943 WHERE has_schema_privilege(n.oid,'USAGE')
944 AND n.nspname NOT LIKE 'pg!_%' escape '!'
945 AND has_table_privilege(c.oid,'SELECT')
946 AND (NOT a.attisdropped)
947 AND d.adsrc ~ '^nextval'
951 CASE WHEN strpos(seq_name, '.') > 0 THEN
952 substring(seq_name, 1,strpos(seq_name,'.')-1)
957 GROUP BY seq_name HAVING count(*)=1
960 while ($cs->fetch()) {
963 foreach($cmds as $cmd) {
964 $cs = DB_DataObject::factory('core_enum');
968 $cs = DB_DataObject::factory('core_enum');
970 SELECT 'SELECT SETVAL(' ||
971 quote_literal(quote_ident(nspname) || '.' || quote_ident(S.relname)) ||
972 ', MAX(' || quote_ident(C.attname)|| ')::integer ) FROM ' || nspname || '.' || quote_ident(T.relname)|| ';' as cmd
978 WHERE S.relkind = 'S'
980 AND D.refobjid = T.oid
981 AND D.refobjid = C.attrelid
982 AND D.refobjsubid = C.attnum
983 AND NS.oid = T.relnamespace
987 while ($cs->fetch()) {
990 foreach($cmds as $cmd) {
991 $cs = DB_DataObject::factory('core_enum');
998 var $extensions = array(
1003 function runExtensions()
1006 $ff = HTML_Flexyframework::get();
1008 $dburl = parse_url($ff->DB_DataObject['database']);
1010 $dbtype = $dburl['scheme'];
1012 foreach($this->extensions as $ext) {
1014 $scls = ucfirst($dbtype). $ext;
1015 $cls = __CLASS__ . '_'. $scls;
1016 $fn = implode('/',explode('_', $cls)).'.php';
1017 if (!file_exists(__DIR__.'/UpdateDatabase/'. $scls .'.php')) {
1028 function checkSystem()
1030 // most of these are from File_Convert...
1032 // these are required - and have simple dependancies.
1033 require_once 'System.php';
1039 'rsvg-convert', //librsvg2-bin
1045 // these are prefered - but may have complicated depenacies
1050 'html2text', // not availabe in debian squeeze
1051 'pdftocairo', //poppler-utils - not available in debian squeeze.
1061 foreach($req as $r) {
1062 if (!System::which($r)) {
1068 $this->jerr("Missing these programs - need installing\n" . implode("\n",$res));
1070 foreach($pref as $r) {
1071 if (!System::which($r)) {
1077 echo "WARNING: Missing these programs - they may need installing\n". implode("\n",$res);