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);
164 * imports SQL files from all DataObjects directories....
166 * except any matching /migrate/
171 // loop through all the modules, and see if they have a importSQL method?
174 $ff = HTML_Flexyframework::get();
176 $dburl = parse_url($ff->DB_DataObject['database']);
178 //$this->{'import' . $url['scheme']}($url);
180 $dbtype = $dburl['scheme'];
181 $dirmethod = 'import' . $dburl['scheme'] . 'dir';
186 $ar = $this->modulesList();
190 echo "Importing SQL from module $m\n";
191 if (!empty($this->opts['only-module-sql']) && $m != $this->opts['only-module-sql']) {
196 // check to see if the class has
200 $file = $this->rootDir. "/Pman/$m/UpdateDatabase.php";
201 if($m != 'Core' && file_exists($file)){
204 $class = "Pman_{$m}_UpdateDatabase";
206 if(method_exists($x, 'importModuleSQL')){
207 echo "Importing SQL from module $m using Module::importModuleSQL\n";
208 $x->opts = $this->opts;
209 $x->rootDir = $this->rootDir;
210 $x->importModuleSQL($dburl);
215 echo "Importing SQL from module $m\n";
218 // if init has been called
220 if (!empty($this->opts['init'])) {
221 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}.init");
227 $fd = $this->rootDir. "/Pman/$m/DataObjects";
229 $this->{$dirmethod}($dburl, $fd);
231 // new -- sql directory..
232 // new style will not support migrate ... they have to go into mysql-migrate.... directories..
233 // new style will not support pg.sql etc.. naming - that's what the direcotries are for..
235 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/sql");
236 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}");
240 if (!empty($this->opts['init']) && file_exists($this->rootDir. "/Pman/$m/{$dbtype}.initdata")) {
241 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
243 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}.initdata");
244 $this->{'fixSequences'. $dbtype}();
256 /** -------------- code to handle importing a whole directory of files into the database ------- **/
259 function importpgsqldir($url, $dir, $disable_triggers = false)
261 require_once 'System.php';
262 $cat = System::which('cat');
263 $psql = System::which('psql');
266 if (!empty($url['pass'])) {
267 putenv("PGPASSWORD=". $url['pass']);
271 ' -h ' . $url['host'] .
272 ' -U' . escapeshellarg($url['user']) .
273 ' ' . basename($url['path']);
276 echo $psql_cmd . "\n" ;
277 echo "scan : $dir\n";
279 $files = array($dir);
284 $files = glob($dir.'/*.sql');
285 uksort($files, 'strcasecmp');
287 //$lsort = create_function('$a,$b','return strlen($a) > strlen($b) ? 1 : -1;');
288 //usort($files, $lsort);
292 foreach($files as $bfn) {
295 if (preg_match('/migrate/i', basename($bfn))) { // skip migration scripts at present..
298 if (preg_match('#\.[a-z]{2}\.sql#i', basename($bfn))
299 && !preg_match('#\.pg\.sql#i', basename($bfn))
300 ) { // skip migration scripts at present..
305 if (!preg_match('/pgsql/', basename($dir) )) {
306 if ( !preg_match('#\.pg\.sql$#', basename($bfn))) {
307 $fn = $this->convertToPG($bfn);
311 // files ending in .pg.sql are native postgres files.. ## depricated
314 $cmd = "$psql_cmd < " . escapeshellarg($fn ? $fn : $bfn) . ' 2>&1' ;
316 echo "$bfn: $cmd ". ($this->cli ? "\n" : "<BR>\n");
333 * mysql - does not support conversions.
339 function importmysqldir($dburl, $dir)
341 echo "Import MYSQL :: $dir\n";
344 require_once 'System.php';
345 $cat = System::which('cat');
346 $mysql = System::which('mysql');
350 $mysql_cmd = $mysql .
351 ' -h ' . $dburl['host'] .
352 ' -u' . escapeshellarg($dburl['user']) .
353 (!empty($dburl['pass']) ? ' -p' . escapeshellarg($dburl['pass']) : '') .
354 ' ' . basename($dburl['path']);
355 //echo $mysql_cmd . "\n" ;
357 $files = glob($dir.'/*.sql');
358 uksort($files, 'strcasecmp');
361 foreach($files as $fn) {
364 if (preg_match('/migrate/i', basename($fn))) { // skip migration scripts at present..
367 // .my.sql but not .pg.sql
368 if (preg_match('#\.[a-z]{2}\.sql#i', basename($fn))
369 && !preg_match('#\.my\.sql#i', basename($fn))
370 ) { // skip migration scripts at present..
373 if (!strlen(trim($fn))) {
377 $cmd = "$mysql_cmd -f < " . escapeshellarg($fn) ;
379 echo basename($dir).'/'. basename($fn) . '::' . $cmd. ($this->cli ? "\n" : "<BR>\n");
392 * simple regex based convert mysql to pgsql...
394 function convertToPG($src)
396 //echo "Convert $src\n";
398 $fn = $this->tempName('sql');
400 $ret = array( ); // pad it a bit.
401 $extra = array("", "" );
404 foreach(file($src) as $l) {
407 if (!strlen($l) || $l[0] == '#') {
411 if (preg_match('#create\s+table\s+([a-z0-9_]+)#i', $l, $m)) {
414 if (preg_match('#create\s+table\s+\`([a-z0-9_]+)\`#i', $l, $m)) {
415 $tbl = 'shop_' . strtolower($m[1]);
416 $l = preg_replace('#create\s+table\s+\`([a-z0-9_]+)\`#i', "CREATE TABLE {$tbl}", $l);
418 if (preg_match('#\`([a-z0-9_]+)\`#i', $l, $m) && !preg_match('#alter\s+table\s+#i', $l)) {
419 $l = preg_replace('#\`([a-z0-9_]+)\`#i', "{$m[1]}_name", $l);
422 if ($tbl && preg_match('#auto_increment#i', $l, $m)) {
423 $l = preg_replace('#auto_increment#i', "default nextval('{$tbl}_seq')", $l);
424 $extra[] = "create sequence {$tbl}_seq;";
428 if (preg_match('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', $l, $m)){
429 $l = preg_replace('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', "ALTER TABLE {$tbl}", $l);
432 // enum value -- use the text instead..
434 if ($tbl && preg_match('#([\w]+)\s+(enum\([\w|\W]+\))#i', $l, $m)) {
435 $l = preg_replace('#enum\([\w|\W]+\)#i', "TEXT", $l);
437 // ignore the alter enum
438 if ($tbl && preg_match('#alter\s+table\s+([\w|\W]+)\s+enum\([\w|\W]+\)#i', $l, $m)) {
442 // UNIQUE KEY .. ignore
443 if ($tbl && preg_match('#UNIQUE KEY#i', $l, $m)) {
444 $last = array_pop($ret);
445 $ret[] = trim($last, ",");
449 if ($tbl && preg_match('#RENAME\s+TO#i', $l, $m)) {
453 if ($tbl && preg_match('#change\s+column#i', $l, $m)) {
457 // INDEX lookup ..ignore
458 if ($tbl && preg_match('#INDEX lookup+([\w|\W]+)#i', $l, $m)) {
459 $last = array_pop($ret);
460 $ret[] = trim($last, ",");
465 // CREATE INDEX ..ignore
466 if (preg_match('#alter\s+table\s+([a-z0-9_]+)\s+add\s+index\s+#i', $l, $m)) {
467 // $l = "CREATE INDEX {$m[1]}_{$m[2]} ON {$m[1]} {$m[3]}";
472 $l = preg_replace('#int\([0-9]+\)#i', 'INT', $l);
474 $l = preg_replace('# datetime#i', ' TIMESTAMP WITHOUT TIME ZONE', $l);
475 $l = preg_replace('# blob#i', ' TEXT', $l);
476 $l = preg_replace('# longtext#i', ' TEXT', $l);
477 $l = preg_replace('# tinyint#i', ' INT', $l);
483 $ret = array_merge($extra,$ret);
484 // echo implode("\n", $ret); exit;
486 file_put_contents($fn, implode("\n", $ret));
492 function checkOpts($opts)
496 foreach($opts as $o=>$v) {
497 if (!preg_match('/^json-/', $o) || empty($v)) {
500 if (!file_exists($v)) {
501 die("File does not exist : OPTION --{$o} = {$v} \n");
505 $modules = array_reverse($this->modulesList());
507 // move 'project' one to the end...
509 foreach ($modules as $module){
510 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
511 if($module == 'Core' || !file_exists($file)){
515 $class = "Pman_{$module}_UpdateDatabase";
517 if(!method_exists($x, 'checkOpts')){
520 $x->checkOpts($opts);
524 static function jsonImportFromArray($opts)
526 foreach($opts as $o=>$v) {
527 if (!preg_match('/^json-/', $o) || empty($v)) {
530 $type = str_replace('_', '-', substr($o,5));
532 $data= json_decode(file_get_contents($v),true);
533 $pg = HTML_FlexyFramework::get()->page;
534 DB_DataObject::factory($type)->importFromArray($pg ,$data,$opts);
544 function runUpdateModulesData()
548 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
549 echo "Running jsonImportFromArray\n";
550 Pman_Core_UpdateDatabase::jsonImportFromArray($this->opts);
553 echo "Running updateData on modules\n";
557 $modules = array_reverse($this->modulesList());
559 // move 'project' one to the end...
561 foreach ($modules as $module){
562 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
563 if($module == 'Core' || !file_exists($file)){
568 $class = "Pman_{$module}_UpdateDatabase";
570 if(!method_exists($x, 'updateData')){
580 function updateDataEnums()
583 $enum = DB_DataObject::Factory('core_enum');
584 //DB_DAtaObject::debugLevel(1);
589 'name' => 'COMPTYPE',
590 'display_name' => 'Company Types',
591 'is_system_enum' => 1,
595 'display_name' => 'Owner',
596 'seqid' => 999, // last...
597 'is_system_enum' => 1,
604 'name' => 'HtmlEditor.font-family',
605 'display_name' => 'HTML Editor font families',
606 'is_system_enum' => 1,
609 'name' => 'Helvetica,Arial,sans-serif',
610 'display_name' => 'Helvetica',
615 'name' => 'Courier New',
616 'display_name' => 'Courier',
621 'display_name' => 'Tahoma',
625 'name' => 'Times New Roman,serif',
626 'display_name' => 'Times',
631 'display_name' => 'Verdana',
643 function updateDataGroups()
646 $groups = DB_DataObject::factory('groups');
647 $groups->initGroups();
649 $groups->initDatabase($this,array(
651 'name' => 'bcc-email', // group who are bcc'ed on all requests.
652 'type' => 0, // system
655 'name' => 'system-email-from',
656 'type' => 0, // system
662 function updateDataCompanies()
665 // fix comptypes enums..
666 $c = DB_DataObject::Factory('Companies');
668 $c->selectAdd('distinct(comptype) as comptype');
669 $c->whereAdd("comptype != ''");
672 foreach($c->fetchAll('comptype') as $cts) {
676 $ctb[]= array( 'etype'=>'COMPTYPE', 'name' => $cts, 'display_name' => ucfirst(strtolower($cts)));
679 $c = DB_DataObject::Factory('core_enum');
682 //DB_DataObject::debugLevel(1);
684 $c = DB_DataObject::Factory('Companies');
688 comptype_id = (SELECT id FROM core_enum where etype='comptype' and name=Companies.comptype LIMIT 1)
701 function updateData()
704 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
705 $this->updateDataEnums();
706 $this->updateDataGroups();
707 $this->updateDataCompanies();
709 $c = DB_DataObject::Factory('I18n');
717 /** ------------- schema fixing ... there is an issue with data imported having the wrong sequence names... --- */
719 function fixSequencesMysql()
724 function fixSequencesPgsql()
728 //DB_DataObject::debugLevel(1);
729 $cs = DB_DataObject::factory('core_enum');
733 CASE WHEN strpos(seq_name, '.') > 0 THEN
736 quote_ident(min(schema_name)) ||'.'|| quote_ident(min(seq_name))
739 ||' OWNED BY '|| quote_ident(min(schema_name)) || '.' ||
740 quote_ident(min(table_name)) ||'.'|| quote_ident(min(column_name)) ||';' as cmd
744 n.nspname AS schema_name,
745 c.relname AS table_name,
746 a.attname AS column_name,
747 regexp_replace(regexp_replace(d.adsrc, E'nextval\\\\(+[''\\\"]*', ''),E'[''\\\"]*::.*\$','') AS seq_name
749 JOIN pg_attribute a ON (c.oid=a.attrelid)
750 JOIN pg_attrdef d ON (a.attrelid=d.adrelid AND a.attnum=d.adnum)
751 JOIN pg_namespace n ON (c.relnamespace=n.oid)
752 WHERE has_schema_privilege(n.oid,'USAGE')
753 AND n.nspname NOT LIKE 'pg!_%' escape '!'
754 AND has_table_privilege(c.oid,'SELECT')
755 AND (NOT a.attisdropped)
756 AND d.adsrc ~ '^nextval'
760 CASE WHEN strpos(seq_name, '.') > 0 THEN
761 substring(seq_name, 1,strpos(seq_name,'.')-1)
766 GROUP BY seq_name HAVING count(*)=1
769 while ($cs->fetch()) {
772 foreach($cmds as $cmd) {
773 $cs = DB_DataObject::factory('core_enum');
777 $cs = DB_DataObject::factory('core_enum');
779 SELECT 'SELECT SETVAL(' ||
780 quote_literal(quote_ident(nspname) || '.' || quote_ident(S.relname)) ||
781 ', MAX(' || quote_ident(C.attname)|| ')::integer ) FROM ' || nspname || '.' || quote_ident(T.relname)|| ';' as cmd
787 WHERE S.relkind = 'S'
789 AND D.refobjid = T.oid
790 AND D.refobjid = C.attrelid
791 AND D.refobjsubid = C.attnum
792 AND NS.oid = T.relnamespace
796 while ($cs->fetch()) {
799 foreach($cmds as $cmd) {
800 $cs = DB_DataObject::factory('core_enum');