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'));
114 $ff = HTML_FlexyFramework::get();
115 if (!empty($ff->cli)) {
120 parent::getAuth(); // load company!
121 $au = $this->getAuthUser();
122 if (!$au || $au->company()->comptype != 'OWNER') {
123 $this->jerr("Not authenticated", array('authFailure' => true));
125 $this->authUser = $au;
129 function get($args, $opts)
131 PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, array($this, 'onPearError'));
134 //$this->fixSequencesPgsql();exit;
137 // ask all the modules to verify the opts
139 $this->checkOpts($opts);
143 if (empty($opts['data-only'])) {
146 if (!empty($opts['only-module-sql'])) {
150 $this->runUpdateModulesData();
153 if (!empty($opts['add-company'])) {
154 // make sure we have a good cache...?
156 DB_DataObject::factory('companies')->initCompanies($this, $opts);
159 $this->runExtensions();
167 * imports SQL files from all DataObjects directories....
169 * except any matching /migrate/
174 // loop through all the modules, and see if they have a importSQL method?
177 $ff = HTML_Flexyframework::get();
179 $dburl = parse_url($ff->DB_DataObject['database']);
181 //$this->{'import' . $url['scheme']}($url);
183 $dbtype = $dburl['scheme'];
184 $dirmethod = 'import' . $dburl['scheme'] . 'dir';
189 $ar = $this->modulesList();
193 echo "Importing SQL from module $m\n";
194 if (!empty($this->opts['only-module-sql']) && $m != $this->opts['only-module-sql']) {
199 // check to see if the class has
203 $file = $this->rootDir. "/Pman/$m/UpdateDatabase.php";
204 if($m != 'Core' && file_exists($file)){
207 $class = "Pman_{$m}_UpdateDatabase";
209 if(method_exists($x, 'importModuleSQL')){
210 echo "Importing SQL from module $m using Module::importModuleSQL\n";
211 $x->opts = $this->opts;
212 $x->rootDir = $this->rootDir;
213 $x->importModuleSQL($dburl);
218 echo "Importing SQL from module $m\n";
221 // if init has been called
223 if (!empty($this->opts['init'])) {
224 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}.init");
230 $fd = $this->rootDir. "/Pman/$m/DataObjects";
232 $this->{$dirmethod}($dburl, $fd);
234 // new -- sql directory..
235 // new style will not support migrate ... they have to go into mysql-migrate.... directories..
236 // new style will not support pg.sql etc.. naming - that's what the direcotries are for..
238 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/sql");
239 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}");
243 if (!empty($this->opts['init']) && file_exists($this->rootDir. "/Pman/$m/{$dbtype}.initdata")) {
244 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
246 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}.initdata");
247 $this->{'fixSequences'. $dbtype}();
259 /** -------------- code to handle importing a whole directory of files into the database ------- **/
262 function importpgsqldir($url, $dir, $disable_triggers = false)
264 $ff = HTML_FlexyFramework::get();
266 require_once 'System.php';
267 $cat = System::which('cat');
268 $psql = System::which('psql');
271 if (!empty($url['pass'])) {
272 putenv("PGPASSWORD=". $url['pass']);
276 ' -h ' . $url['host'] .
277 ' -U' . escapeshellarg($url['user']) .
278 ' ' . basename($url['path']);
281 echo $psql_cmd . "\n" ;
282 echo "scan : $dir\n";
285 $files = array($dir);
290 $files = glob($dir.'/*.sql');
291 uksort($files, 'strcasecmp');
293 //$lsort = create_function('$a,$b','return strlen($a) > strlen($b) ? 1 : -1;');
294 //usort($files, $lsort);
297 foreach($files as $bfn) {
300 if (preg_match('/migrate/i', basename($bfn))) { // skip migration scripts at present..
303 if (preg_match('#\.[a-z]{2}\.sql#i', basename($bfn))
304 && !preg_match('#\.pg\.sql#i', basename($bfn))
305 ) { // skip migration scripts at present..
310 if (!preg_match('/pgsql/', basename($dir) )) {
311 if ( !preg_match('#\.pg\.sql$#', basename($bfn))) {
312 $fn = $this->convertToPG($bfn);
316 // files ending in .pg.sql are native postgres files.. ## depricated
319 $cmd = "$psql_cmd < " . escapeshellarg($fn ? $fn : $bfn) . ' 2>&1' ;
321 echo "$bfn: $cmd ". ($ff->cli ? "\n" : "<BR>\n");
337 * mysql - does not support conversions.
343 function importmysqldir($dburl, $dir)
346 $this->fixMysqlInnodb(); /// run once
348 echo "Import MYSQL :: $dir\n";
351 require_once 'System.php';
352 $cat = System::which('cat');
353 $mysql = System::which('mysql');
357 $mysql_cmd = $mysql .
358 ' -h ' . $dburl['host'] .
359 ' -u' . escapeshellarg($dburl['user']) .
360 (!empty($dburl['pass']) ? ' -p' . escapeshellarg($dburl['pass']) : '') .
361 ' ' . basename($dburl['path']);
362 //echo $mysql_cmd . "\n" ;
364 $files = glob($dir.'/*.sql');
365 uksort($files, 'strcasecmp');
368 foreach($files as $fn) {
371 if (preg_match('/migrate/i', basename($fn))) { // skip migration scripts at present..
374 // .my.sql but not .pg.sql
375 if (preg_match('#\.[a-z]{2}\.sql#i', basename($fn))
376 && !preg_match('#\.my\.sql#i', basename($fn))
377 ) { // skip migration scripts at present..
380 if (!strlen(trim($fn))) {
384 $cmd = "$mysql_cmd -f < " . escapeshellarg($fn) ;
386 echo basename($dir).'/'. basename($fn) . '::' . $cmd. ($this->cli ? "\n" : "<BR>\n");
399 * simple regex based convert mysql to pgsql...
401 function convertToPG($src)
403 //echo "Convert $src\n";
405 $fn = $this->tempName('sql');
407 $ret = array( ); // pad it a bit.
408 $extra = array("", "" );
411 foreach(file($src) as $l) {
414 if (!strlen($l) || $l[0] == '#') {
418 if (preg_match('#create\s+table\s+([a-z0-9_]+)#i', $l, $m)) {
421 if (preg_match('#create\s+table\s+\`([a-z0-9_]+)\`#i', $l, $m)) {
422 $tbl = 'shop_' . strtolower($m[1]);
423 $l = preg_replace('#create\s+table\s+\`([a-z0-9_]+)\`#i', "CREATE TABLE {$tbl}", $l);
425 if (preg_match('#\`([a-z0-9_]+)\`#i', $l, $m) && !preg_match('#alter\s+table\s+#i', $l)) {
426 $l = preg_replace('#\`([a-z0-9_]+)\`#i', "{$m[1]}_name", $l);
429 if ($tbl && preg_match('#auto_increment#i', $l, $m)) {
430 $l = preg_replace('#auto_increment#i', "default nextval('{$tbl}_seq')", $l);
431 $extra[] = "create sequence {$tbl}_seq;";
435 if (preg_match('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', $l, $m)){
436 $l = preg_replace('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', "ALTER TABLE {$tbl}", $l);
439 // enum value -- use the text instead..
441 if ($tbl && preg_match('#([\w]+)\s+(enum\([\w|\W]+\))#i', $l, $m)) {
442 $l = preg_replace('#enum\([\w|\W]+\)#i', "TEXT", $l);
444 // ignore the alter enum
445 if ($tbl && preg_match('#alter\s+table\s+([\w|\W]+)\s+enum\([\w|\W]+\)#i', $l, $m)) {
449 // UNIQUE KEY .. ignore
450 if ($tbl && preg_match('#UNIQUE KEY#i', $l, $m)) {
451 $last = array_pop($ret);
452 $ret[] = trim($last, ",");
456 if ($tbl && preg_match('#RENAME\s+TO#i', $l, $m)) {
460 if ($tbl && preg_match('#change\s+column#i', $l, $m)) {
464 // INDEX lookup ..ignore
465 if ($tbl && preg_match('#INDEX lookup+([\w|\W]+)#i', $l, $m)) {
466 $last = array_pop($ret);
467 $ret[] = trim($last, ",");
472 // CREATE INDEX ..ignore
473 if (preg_match('#alter\s+table\s+([a-z0-9_]+)\s+add\s+index\s+#i', $l, $m)) {
474 // $l = "CREATE INDEX {$m[1]}_{$m[2]} ON {$m[1]} {$m[3]}";
479 $l = preg_replace('#int\([0-9]+\)#i', 'INT', $l);
481 $l = preg_replace('# datetime#i', ' TIMESTAMP WITHOUT TIME ZONE', $l);
482 $l = preg_replace('# blob#i', ' TEXT', $l);
483 $l = preg_replace('# longtext#i', ' TEXT', $l);
484 $l = preg_replace('# tinyint#i', ' INT', $l);
490 $ret = array_merge($extra,$ret);
491 // echo implode("\n", $ret); exit;
493 file_put_contents($fn, implode("\n", $ret));
499 function checkOpts($opts)
503 foreach($opts as $o=>$v) {
504 if (!preg_match('/^json-/', $o) || empty($v)) {
507 if (!file_exists($v)) {
508 die("File does not exist : OPTION --{$o} = {$v} \n");
512 $modules = array_reverse($this->modulesList());
514 // move 'project' one to the end...
516 foreach ($modules as $module){
517 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
518 if($module == 'Core' || !file_exists($file)){
522 $class = "Pman_{$module}_UpdateDatabase";
524 if(!method_exists($x, 'checkOpts')){
527 $x->checkOpts($opts);
531 static function jsonImportFromArray($opts)
533 foreach($opts as $o=>$v) {
534 if (!preg_match('/^json-/', $o) || empty($v)) {
537 $type = str_replace('_', '-', substr($o,5));
539 $data= json_decode(file_get_contents($v),true);
540 $pg = HTML_FlexyFramework::get()->page;
541 DB_DataObject::factory($type)->importFromArray($pg ,$data,$opts);
551 function runUpdateModulesData()
555 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
556 echo "Running jsonImportFromArray\n";
557 Pman_Core_UpdateDatabase::jsonImportFromArray($this->opts);
560 echo "Running updateData on modules\n";
564 $modules = array_reverse($this->modulesList());
566 // move 'project' one to the end...
568 foreach ($modules as $module){
569 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
570 if($module == 'Core' || !file_exists($file)){
575 $class = "Pman_{$module}_UpdateDatabase";
577 if(!method_exists($x, 'updateData')){
587 function updateDataEnums()
590 $enum = DB_DataObject::Factory('core_enum');
591 //DB_DAtaObject::debugLevel(1);
596 'name' => 'COMPTYPE',
597 'display_name' => 'Company Types',
598 'is_system_enum' => 1,
602 'display_name' => 'Owner',
603 'seqid' => 999, // last...
604 'is_system_enum' => 1,
611 'name' => 'HtmlEditor.font-family',
612 'display_name' => 'HTML Editor font families',
613 'is_system_enum' => 1,
616 'name' => 'Helvetica,Arial,sans-serif',
617 'display_name' => 'Helvetica',
622 'name' => 'Courier New',
623 'display_name' => 'Courier',
628 'display_name' => 'Tahoma',
632 'name' => 'Times New Roman,serif',
633 'display_name' => 'Times',
638 'display_name' => 'Verdana',
650 function updateDataGroups()
653 $groups = DB_DataObject::factory('groups');
654 $groups->initGroups();
656 $groups->initDatabase($this,array(
658 'name' => 'bcc-email', // group who are bcc'ed on all requests.
659 'type' => 0, // system
662 'name' => 'system-email-from',
663 'type' => 0, // system
666 'name' => 'core-person-signup-bcc',
667 'type' => 0, // system
673 function updateDataCompanies()
676 // fix comptypes enums..
677 $c = DB_DataObject::Factory('Companies');
679 $c->selectAdd('distinct(comptype) as comptype');
680 $c->whereAdd("comptype != ''");
683 foreach($c->fetchAll('comptype') as $cts) {
687 $ctb[]= array( 'etype'=>'COMPTYPE', 'name' => $cts, 'display_name' => ucfirst(strtolower($cts)));
690 $c = DB_DataObject::Factory('core_enum');
693 //DB_DataObject::debugLevel(1);
695 $c = DB_DataObject::Factory('Companies');
699 comptype_id = (SELECT id FROM core_enum where etype='comptype' and name=Companies.comptype LIMIT 1)
712 function updateData()
715 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
716 $this->updateDataEnums();
717 $this->updateDataGroups();
718 $this->updateDataCompanies();
720 $c = DB_DataObject::Factory('I18n');
728 function fixMysqlInnodb()
731 static $done_check = false;
735 // innodb in single files is far more efficient that MYD or one big innodb file.
736 // first check if database is using this format.
737 $db = DB_DataObject::factory('core_enum');
738 $db->query("show variables like 'innodb_file_per_table'");
740 if ($db->Value == 'OFF') {
741 die("Error: set innodb_file_per_table = 1 in my.cnf\n\n");
755 /** ------------- schema fixing ... there is an issue with data imported having the wrong sequence names... --- */
757 function fixSequencesMysql()
762 function fixSequencesPgsql()
766 //DB_DataObject::debugLevel(1);
767 $cs = DB_DataObject::factory('core_enum');
771 CASE WHEN strpos(seq_name, '.') > 0 THEN
774 quote_ident(min(schema_name)) ||'.'|| quote_ident(min(seq_name))
777 ||' OWNED BY '|| quote_ident(min(schema_name)) || '.' ||
778 quote_ident(min(table_name)) ||'.'|| quote_ident(min(column_name)) ||';' as cmd
782 n.nspname AS schema_name,
783 c.relname AS table_name,
784 a.attname AS column_name,
785 regexp_replace(regexp_replace(d.adsrc, E'nextval\\\\(+[''\\\"]*', ''),E'[''\\\"]*::.*\$','') AS seq_name
787 JOIN pg_attribute a ON (c.oid=a.attrelid)
788 JOIN pg_attrdef d ON (a.attrelid=d.adrelid AND a.attnum=d.adnum)
789 JOIN pg_namespace n ON (c.relnamespace=n.oid)
790 WHERE has_schema_privilege(n.oid,'USAGE')
791 AND n.nspname NOT LIKE 'pg!_%' escape '!'
792 AND has_table_privilege(c.oid,'SELECT')
793 AND (NOT a.attisdropped)
794 AND d.adsrc ~ '^nextval'
798 CASE WHEN strpos(seq_name, '.') > 0 THEN
799 substring(seq_name, 1,strpos(seq_name,'.')-1)
804 GROUP BY seq_name HAVING count(*)=1
807 while ($cs->fetch()) {
810 foreach($cmds as $cmd) {
811 $cs = DB_DataObject::factory('core_enum');
815 $cs = DB_DataObject::factory('core_enum');
817 SELECT 'SELECT SETVAL(' ||
818 quote_literal(quote_ident(nspname) || '.' || quote_ident(S.relname)) ||
819 ', MAX(' || quote_ident(C.attname)|| ')::integer ) FROM ' || nspname || '.' || quote_ident(T.relname)|| ';' as cmd
825 WHERE S.relkind = 'S'
827 AND D.refobjid = T.oid
828 AND D.refobjid = C.attrelid
829 AND D.refobjsubid = C.attnum
830 AND NS.oid = T.relnamespace
834 while ($cs->fetch()) {
837 foreach($cmds as $cmd) {
838 $cs = DB_DataObject::factory('core_enum');
845 var $extensions = array(
850 function runExtensions()
853 $ff = HTML_Flexyframework::get();
855 $dburl = parse_url($ff->DB_DataObject['database']);
857 $dbtype = $dburl['scheme'];
859 foreach($this->extensions as $ext) {
861 $scls = ucfirst($dbtype). $ext;
862 $cls = __CLASS__ . '_'. $scls;
863 $fn = implode('/',explode('_', $cls)).'.php';
864 if (!file_exists(__DIR__.'/UpdateDatabase/'. $scls .'.php')) {