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',
65 'json-person' => array(
66 'desc' => 'Person JSON file',
74 static function cli_opts()
77 $ret = self::$cli_opts;
78 $ff = HTML_FlexyFramework::get();
80 $mods = $a->modulesList();
81 foreach($mods as $m) {
83 $fd = $ff->rootDir. "/Pman/$m/UpdateDatabase.php";
84 if (!file_exists($fd)) {
90 $cls = new ReflectionClass('Pman_'. $m . '_UpdateDatabase');
92 $ret = array_merge($ret, $cls->getStaticPropertyValue('cli_opts'));
107 $ff = HTML_FlexyFramework::get();
108 if (!empty($ff->cli)) {
113 parent::getAuth(); // load company!
114 $au = $this->getAuthUser();
115 if (!$au || $au->company()->comptype != 'OWNER') {
116 $this->jerr("Not authenticated", array('authFailure' => true));
118 $this->authUser = $au;
122 function get($args, $opts)
125 PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, array($this, 'onPearError'));
128 //$this->fixSequencesPgsql();exit;
131 // ask all the modules to verify the opts
133 $this->checkOpts($opts);
137 if (empty($opts['data-only'])) {
140 if (!empty($opts['only-module-sql'])) {
144 $this->runUpdateModulesData();
147 if (!empty($opts['add-company'])) {
148 // make sure we have a good cache...?
150 DB_DataObject::factory('companies')->initCompanies($this, $opts);
158 * imports SQL files from all DataObjects directories....
160 * except any matching /migrate/
165 $ff = HTML_Flexyframework::get();
167 $url = parse_url($ff->DB_DataObject['database']);
169 $this->{'import' . $url['scheme']}($url);
174 * mysql - does not support conversions.
180 function importmysqldir($dburl, $dir)
182 echo "Import MYSQL :: $dir\n";
185 require_once 'System.php';
186 $cat = System::which('cat');
187 $mysql = System::which('mysql');
191 $mysql_cmd = $mysql .
192 ' -h ' . $dburl['host'] .
193 ' -u' . escapeshellarg($dburl['user']) .
194 (!empty($dburl['pass']) ? ' -p' . escapeshellarg($dburl['pass']) : '') .
195 ' ' . basename($dburl['path']);
196 //echo $mysql_cmd . "\n" ;
198 $files = glob($dir.'/*.sql');
199 uksort($files, 'strcasecmp');
202 foreach($files as $fn) {
205 if (preg_match('/migrate/i', basename($fn))) { // skip migration scripts at present..
208 // .my.sql but not .pg.sql
209 if (preg_match('#\.[a-z]{2}\.sql#i', basename($fn))
210 && !preg_match('#\.my\.sql#i', basename($fn))
211 ) { // skip migration scripts at present..
214 if (!strlen(trim($fn))) {
218 $cmd = "$mysql_cmd -f < " . escapeshellarg($fn) ;
220 echo basename($dir).'/'. basename($fn) . '::' . $cmd. ($this->cli ? "\n" : "<BR>\n");
233 function importmysql($dburl)
236 // hide stuff for web..
237 $ar = $this->modulesList();
241 // old -- DAtaObjects/*.sql
245 if (!empty($this->opts['only-module-sql']) && $m != $this->opts['only-module-sql']) {
249 $fd = $this->rootDir. "/Pman/$m/DataObjects";
251 $this->importmysqldir($dburl, $fd);
253 // new -- sql directory..
254 // new style will not support migrate ... they have to go into mysql-migrate.... directories..
255 // new style will not support pg.sql etc.. naming - that's what the direcotries are for..
257 $this->importmysqldir($dburl, $this->rootDir. "/Pman/$m/sql");
258 $this->importmysqldir($dburl, $this->rootDir. "/Pman/$m/mysql");
267 * postgresql import..
269 function importpgsql($dburl)
272 // hide stuff for web..
277 $ar = $this->modulesList();
281 echo "Importing SQL from module $m\n";
282 if (!empty($this->opts['only-module-sql']) && $m != $this->opts['only-module-sql']) {
285 echo "Importing SQL from module $m\n";
286 // if init has been called
288 if (!empty($this->opts['init'])) {
289 $this->importpgsqldir($dburl, $this->rootDir. "/Pman/$m/pgsql.init");
295 $fd = $this->rootDir. "/Pman/$m/DataObjects";
297 $this->importpgsqldir($dburl, $fd);
299 // new -- sql directory..
300 // new style will not support migrate ... they have to go into mysql-migrate.... directories..
301 // new style will not support pg.sql etc.. naming - that's what the direcotries are for..
303 $this->importpgsqldir($dburl, $this->rootDir. "/Pman/$m/sql");
304 $this->importpgsqldir($dburl, $this->rootDir. "/Pman/$m/pgsql");
308 if (!empty($this->opts['init']) && file_exists($this->rootDir. "/Pman/$m/pgsql.initdata")) {
309 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
311 $this->importpgsqldir($dburl, $this->rootDir. "/Pman/$m/pgsql.initdata");
312 $this->fixSequencesPgsql();
321 function importpgsqldir($url, $dir, $disable_triggers = false)
323 require_once 'System.php';
324 $cat = System::which('cat');
325 $psql = System::which('psql');
328 if (!empty($url['pass'])) {
329 putenv("PGPASSWORD=". $url['pass']);
333 ' -h ' . $url['host'] .
334 ' -U' . escapeshellarg($url['user']) .
335 ' ' . basename($url['path']);
338 echo $psql_cmd . "\n" ;
339 echo "scan : $dir\n";
341 $files = glob($dir.'/*.sql');
342 uksort($files, 'strcasecmp');
343 //$lsort = create_function('$a,$b','return strlen($a) > strlen($b) ? 1 : -1;');
344 //usort($files, $lsort);
348 foreach($files as $bfn) {
351 if (preg_match('/migrate/i', basename($bfn))) { // skip migration scripts at present..
354 if (preg_match('#\.[a-z]{2}\.sql#i', basename($bfn))
355 && !preg_match('#\.pg\.sql#i', basename($bfn))
356 ) { // skip migration scripts at present..
361 if (!preg_match('/pgsql/', basename($dir) )) {
362 if ( !preg_match('#\.pg\.sql$#', basename($bfn))) {
363 $fn = $this->convertToPG($bfn);
367 // files ending in .pg.sql are native postgres files.. ## depricated
370 $cmd = "$psql_cmd < " . escapeshellarg($fn ? $fn : $bfn) . ' 2>&1' ;
372 echo "$bfn: $cmd ". ($this->cli ? "\n" : "<BR>\n");
387 * simple regex based convert mysql to pgsql...
389 function convertToPG($src)
391 //echo "Convert $src\n";
393 $fn = $this->tempName('sql');
395 $ret = array( ); // pad it a bit.
396 $extra = array("", "" );
399 foreach(file($src) as $l) {
402 if (!strlen($l) || $l[0] == '#') {
406 if (preg_match('#create\s+table\s+([a-z0-9_]+)#i', $l, $m)) {
409 if (preg_match('#create\s+table\s+\`([a-z0-9_]+)\`#i', $l, $m)) {
410 $tbl = 'shop_' . strtolower($m[1]);
411 $l = preg_replace('#create\s+table\s+\`([a-z0-9_]+)\`#i', "CREATE TABLE {$tbl}", $l);
413 if (preg_match('#\`([a-z0-9_]+)\`#i', $l, $m) && !preg_match('#alter\s+table\s+#i', $l)) {
414 $l = preg_replace('#\`([a-z0-9_]+)\`#i', "{$m[1]}_name", $l);
417 if ($tbl && preg_match('#auto_increment#i', $l, $m)) {
418 $l = preg_replace('#auto_increment#i', "default nextval('{$tbl}_seq')", $l);
419 $extra[] = "create sequence {$tbl}_seq;";
423 if (preg_match('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', $l, $m)){
424 $l = preg_replace('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', "ALTER TABLE {$tbl}", $l);
427 // enum value -- use the text instead..
429 if ($tbl && preg_match('#([\w]+)\s+(enum\([\w|\W]+\))#i', $l, $m)) {
430 $l = preg_replace('#enum\([\w|\W]+\)#i', "TEXT", $l);
432 // ignore the alter enum
433 if ($tbl && preg_match('#alter\s+table\s+([\w|\W]+)\s+enum\([\w|\W]+\)#i', $l, $m)) {
437 // UNIQUE KEY .. ignore
438 if ($tbl && preg_match('#UNIQUE KEY#i', $l, $m)) {
439 $last = array_pop($ret);
440 $ret[] = trim($last, ",");
444 if ($tbl && preg_match('#RENAME\s+TO#i', $l, $m)) {
448 if ($tbl && preg_match('#change\s+column#i', $l, $m)) {
452 // INDEX lookup ..ignore
453 if ($tbl && preg_match('#INDEX lookup+([\w|\W]+)#i', $l, $m)) {
454 $last = array_pop($ret);
455 $ret[] = trim($last, ",");
460 // CREATE INDEX ..ignore
461 if (preg_match('#alter\s+table\s+([a-z0-9_]+)\s+add\s+index\s+#i', $l, $m)) {
462 // $l = "CREATE INDEX {$m[1]}_{$m[2]} ON {$m[1]} {$m[3]}";
467 $l = preg_replace('#int\([0-9]+\)#i', 'INT', $l);
469 $l = preg_replace('# datetime#i', ' TIMESTAMP WITHOUT TIME ZONE', $l);
470 $l = preg_replace('# blob#i', ' TEXT', $l);
471 $l = preg_replace('# longtext#i', ' TEXT', $l);
472 $l = preg_replace('# tinyint#i', ' INT', $l);
478 $ret = array_merge($extra,$ret);
479 // echo implode("\n", $ret); exit;
481 file_put_contents($fn, implode("\n", $ret));
487 function checkOpts($opts)
491 foreach($opts as $o=>$v) {
492 if (!preg_match('/^json-/', $o) || empty($v)) {
495 if (!file_exists($v)) {
496 die("File does not exist : OPTION --{$o} = {$v} \n");
500 $modules = array_reverse($this->modulesList());
502 // move 'project' one to the end...
504 foreach ($modules as $module){
505 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
506 if($module == 'Core' || !file_exists($file)){
510 $class = "Pman_{$module}_UpdateDatabase";
512 if(!method_exists($x, 'checkOpts')){
515 $x->checkOpts($opts);
519 static function jsonImportFromArray($opts)
521 foreach($opts as $o=>$v) {
522 if (!preg_match('/^json-/', $o) || empty($v)) {
525 $type = str_replace('_', '-', substr($o,5));
527 $data= json_decode(file_get_contents($v),true);
528 $pg = HTML_FlexyFramework::get()->page;
529 DB_DataObject::factory($type)->importFromArray($pg ,$data,$opts);
537 function runUpdateModulesData()
541 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
542 echo "Running jsonImportFromArray\n";
543 Pman_Core_UpdateDatabase::jsonImportFromArray($this->opts);
546 echo "Running updateData on modules\n";
550 $modules = array_reverse($this->modulesList());
552 // move 'project' one to the end...
554 foreach ($modules as $module){
555 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
556 if($module == 'Core' || !file_exists($file)){
561 $class = "Pman_{$module}_UpdateDatabase";
563 if(!method_exists($x, 'updateData')){
573 function updateDataEnums()
576 $enum = DB_DataObject::Factory('core_enum');
577 //DB_DAtaObject::debugLevel(1);
582 'name' => 'COMPTYPE',
583 'display_name' => 'Company Types',
584 'is_system_enum' => 1,
588 'display_name' => 'Owner',
589 'seqid' => 999, // last...
590 'is_system_enum' => 1,
597 'name' => 'HtmlEditor.font-family',
598 'display_name' => 'HTML Editor font families',
599 'is_system_enum' => 1,
602 'name' => 'Helvetica,Arial,sans-serif',
603 'display_name' => 'Helvetica',
608 'name' => 'Courier New',
609 'display_name' => 'Courier',
614 'display_name' => 'Tahoma',
618 'name' => 'Times New Roman,serif',
619 'display_name' => 'Times',
624 'display_name' => 'Verdana',
636 function updateDataGroups()
639 $groups = DB_DataObject::factory('groups');
640 $groups->initGroups();
642 $groups->initDatabase($this,array(
644 'name' => 'bcc-email', // group who are bcc'ed on all requests.
645 'type' => 0, // system
652 function updateDataCompanies()
655 // fix comptypes enums..
656 $c = DB_DataObject::Factory('Companies');
658 $c->selectAdd('distinct(comptype) as comptype');
659 $c->whereAdd("comptype != ''");
662 foreach($c->fetchAll('comptype') as $cts) {
666 $ctb[]= array( 'etype'=>'COMPTYPE', 'name' => $cts, 'display_name' => ucfirst(strtolower($cts)));
669 $c = DB_DataObject::Factory('core_enum');
672 //DB_DataObject::debugLevel(1);
674 $c = DB_DataObject::Factory('Companies');
678 comptype_id = (SELECT id FROM core_enum where etype='comptype' and name=Companies.comptype)
691 function updateData()
694 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
695 $this->updateDataEnums();
696 $this->updateDataGroups();
697 $this->updateDataCompanies();
699 $c = DB_DataObject::Factory('I18n');
706 function fixSequencesPgsql()
710 //DB_DataObject::debugLevel(1);
711 $cs = DB_DataObject::factory('core_enum');
715 CASE WHEN strpos(seq_name, '.') > 0 THEN
718 quote_ident(min(schema_name)) ||'.'|| quote_ident(min(seq_name))
721 ||' OWNED BY '|| quote_ident(min(schema_name)) || '.' ||
722 quote_ident(min(table_name)) ||'.'|| quote_ident(min(column_name)) ||';' as cmd
726 n.nspname AS schema_name,
727 c.relname AS table_name,
728 a.attname AS column_name,
729 regexp_replace(regexp_replace(d.adsrc, E'nextval\\\\(+[''\\\"]*', ''),E'[''\\\"]*::.*\$','') AS seq_name
731 JOIN pg_attribute a ON (c.oid=a.attrelid)
732 JOIN pg_attrdef d ON (a.attrelid=d.adrelid AND a.attnum=d.adnum)
733 JOIN pg_namespace n ON (c.relnamespace=n.oid)
734 WHERE has_schema_privilege(n.oid,'USAGE')
735 AND n.nspname NOT LIKE 'pg!_%' escape '!'
736 AND has_table_privilege(c.oid,'SELECT')
737 AND (NOT a.attisdropped)
738 AND d.adsrc ~ '^nextval'
742 CASE WHEN strpos(seq_name, '.') > 0 THEN
743 substring(seq_name, 1,strpos(seq_name,'.')-1)
748 GROUP BY seq_name HAVING count(*)=1
751 while ($cs->fetch()) {
754 foreach($cmds as $cmd) {
755 $cs = DB_DataObject::factory('core_enum');
759 $cs = DB_DataObject::factory('core_enum');
761 SELECT 'SELECT SETVAL(' ||
762 quote_literal(quote_ident(nspname) || '.' || quote_ident(S.relname)) ||
763 ', MAX(' || quote_ident(C.attname)|| ')::integer ) FROM ' || nspname || '.' || quote_ident(T.relname)|| ';' as cmd
769 WHERE S.relkind = 'S'
771 AND D.refobjid = T.oid
772 AND D.refobjid = C.attrelid
773 AND D.refobjsubid = C.attnum
774 AND NS.oid = T.relnamespace
778 while ($cs->fetch()) {
781 foreach($cmds as $cmd) {
782 $cs = DB_DataObject::factory('core_enum');