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" ;
199 foreach(glob($dir.'/*.sql') as $fn) {
202 if (preg_match('/migrate/i', basename($fn))) { // skip migration scripts at present..
205 // .my.sql but not .pg.sql
206 if (preg_match('#\.[a-z]{2}\.sql#i', basename($fn))
207 && !preg_match('#\.my\.sql#i', basename($fn))
208 ) { // skip migration scripts at present..
211 if (!strlen(trim($fn))) {
215 $cmd = "$mysql_cmd -f < " . escapeshellarg($fn) ;
217 echo basename($dir).'/'. basename($fn) . '::' . $cmd. ($this->cli ? "\n" : "<BR>\n");
230 function importmysql($dburl)
233 // hide stuff for web..
234 $ar = $this->modulesList();
238 // old -- DAtaObjects/*.sql
242 if (!empty($this->opts['only-module-sql']) && $m != $this->opts['only-module-sql']) {
246 $fd = $this->rootDir. "/Pman/$m/DataObjects";
248 $this->importmysqldir($dburl, $fd);
250 // new -- sql directory..
251 // new style will not support migrate ... they have to go into mysql-migrate.... directories..
252 // new style will not support pg.sql etc.. naming - that's what the direcotries are for..
254 $this->importmysqldir($dburl, $this->rootDir. "/Pman/$m/sql");
255 $this->importmysqldir($dburl, $this->rootDir. "/Pman/$m/mysql");
264 * postgresql import..
266 function importpgsql($dburl)
269 // hide stuff for web..
274 $ar = $this->modulesList();
278 echo "Importing SQL from module $m\n";
279 if (!empty($this->opts['only-module-sql']) && $m != $this->opts['only-module-sql']) {
282 echo "Importing SQL from module $m\n";
283 // if init has been called
285 if (!empty($this->opts['init'])) {
286 $this->importpgsqldir($dburl, $this->rootDir. "/Pman/$m/pgsql.init");
292 $fd = $this->rootDir. "/Pman/$m/DataObjects";
294 $this->importpgsqldir($dburl, $fd);
296 // new -- sql directory..
297 // new style will not support migrate ... they have to go into mysql-migrate.... directories..
298 // new style will not support pg.sql etc.. naming - that's what the direcotries are for..
300 $this->importpgsqldir($dburl, $this->rootDir. "/Pman/$m/sql");
301 $this->importpgsqldir($dburl, $this->rootDir. "/Pman/$m/pgsql");
305 if (!empty($this->opts['init']) && file_exists($this->rootDir. "/Pman/$m/pgsql.initdata")) {
306 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
308 $this->importpgsqldir($dburl, $this->rootDir. "/Pman/$m/pgsql.initdata");
309 $this->fixSequencesPgsql();
318 function importpgsqldir($url, $dir, $disable_triggers = false)
320 require_once 'System.php';
321 $cat = System::which('cat');
322 $psql = System::which('psql');
325 if (!empty($url['pass'])) {
326 putenv("PGPASSWORD=". $url['pass']);
330 ' -h ' . $url['host'] .
331 ' -U' . escapeshellarg($url['user']) .
332 ' ' . basename($url['path']);
335 echo $psql_cmd . "\n" ;
336 echo "scan : $dir\n";
338 $files = glob($dir.'/*.sql');
339 uksort($files, 'strcasecmp');
340 //$lsort = create_function('$a,$b','return strlen($a) > strlen($b) ? 1 : -1;');
341 //usort($files, $lsort);
345 foreach($files as $bfn) {
348 if (preg_match('/migrate/i', basename($bfn))) { // skip migration scripts at present..
351 if (preg_match('#\.[a-z]{2}\.sql#i', basename($bfn))
352 && !preg_match('#\.pg\.sql#i', basename($bfn))
353 ) { // skip migration scripts at present..
358 if (!preg_match('/pgsql/', basename($dir) )) {
359 if ( !preg_match('#\.pg\.sql$#', basename($bfn))) {
360 $fn = $this->convertToPG($bfn);
364 // files ending in .pg.sql are native postgres files.. ## depricated
367 $cmd = "$psql_cmd < " . escapeshellarg($fn ? $fn : $bfn) . ' 2>&1' ;
369 echo "$bfn: $cmd ". ($this->cli ? "\n" : "<BR>\n");
384 * simple regex based convert mysql to pgsql...
386 function convertToPG($src)
388 //echo "Convert $src\n";
390 $fn = $this->tempName('sql');
392 $ret = array( ); // pad it a bit.
393 $extra = array("", "" );
396 foreach(file($src) as $l) {
399 if (!strlen($l) || $l[0] == '#') {
403 if (preg_match('#create\s+table\s+([a-z0-9_]+)#i', $l, $m)) {
406 if (preg_match('#create\s+table\s+\`([a-z0-9_]+)\`#i', $l, $m)) {
407 $tbl = 'shop_' . strtolower($m[1]);
408 $l = preg_replace('#create\s+table\s+\`([a-z0-9_]+)\`#i', "CREATE TABLE {$tbl}", $l);
410 if (preg_match('#\`([a-z0-9_]+)\`#i', $l, $m) && !preg_match('#alter\s+table\s+#i', $l)) {
411 $l = preg_replace('#\`([a-z0-9_]+)\`#i', "{$m[1]}_name", $l);
414 if ($tbl && preg_match('#auto_increment#i', $l, $m)) {
415 $l = preg_replace('#auto_increment#i', "default nextval('{$tbl}_seq')", $l);
416 $extra[] = "create sequence {$tbl}_seq;";
420 if (preg_match('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', $l, $m)){
421 $l = preg_replace('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', "ALTER TABLE {$tbl}", $l);
424 // enum value -- use the text instead..
426 if ($tbl && preg_match('#([\w]+)\s+(enum\([\w|\W]+\))#i', $l, $m)) {
427 $l = preg_replace('#enum\([\w|\W]+\)#i', "TEXT", $l);
429 // ignore the alter enum
430 if ($tbl && preg_match('#alter\s+table\s+([\w|\W]+)\s+enum\([\w|\W]+\)#i', $l, $m)) {
434 // UNIQUE KEY .. ignore
435 if ($tbl && preg_match('#UNIQUE KEY#i', $l, $m)) {
436 $last = array_pop($ret);
437 $ret[] = trim($last, ",");
441 if ($tbl && preg_match('#RENAME\s+TO#i', $l, $m)) {
445 if ($tbl && preg_match('#change\s+column#i', $l, $m)) {
449 // INDEX lookup ..ignore
450 if ($tbl && preg_match('#INDEX lookup+([\w|\W]+)#i', $l, $m)) {
451 $last = array_pop($ret);
452 $ret[] = trim($last, ",");
457 // CREATE INDEX ..ignore
458 if (preg_match('#alter\s+table\s+([a-z0-9_]+)\s+add\s+index\s+#i', $l, $m)) {
459 // $l = "CREATE INDEX {$m[1]}_{$m[2]} ON {$m[1]} {$m[3]}";
464 $l = preg_replace('#int\([0-9]+\)#i', 'INT', $l);
466 $l = preg_replace('# datetime#i', ' TIMESTAMP WITHOUT TIME ZONE', $l);
467 $l = preg_replace('# blob#i', ' TEXT', $l);
468 $l = preg_replace('# longtext#i', ' TEXT', $l);
469 $l = preg_replace('# tinyint#i', ' INT', $l);
475 $ret = array_merge($extra,$ret);
476 // echo implode("\n", $ret); exit;
478 file_put_contents($fn, implode("\n", $ret));
484 function checkOpts($opts)
488 foreach($opts as $o=>$v) {
489 if (!preg_match('/^json-/', $o) || empty($v)) {
492 if (!file_exists($v)) {
493 die("File does not exist : OPTION --{$o} = {$v} \n");
497 $modules = array_reverse($this->modulesList());
499 // move 'project' one to the end...
501 foreach ($modules as $module){
502 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
503 if($module == 'Core' || !file_exists($file)){
507 $class = "Pman_{$module}_UpdateDatabase";
509 if(!method_exists($x, 'checkOpts')){
512 $x->checkOpts($opts);
516 static function jsonImportFromArray($opts)
518 foreach($opts as $o=>$v) {
519 if (!preg_match('/^json-/', $o) || empty($v)) {
522 $type = str_replace('_', '-', substr($o,5));
524 $data= json_decode(file_get_contents($v),true);
525 $pg = HTML_FlexyFramework::get()->page;
526 DB_DataObject::factory($type)->importFromArray($pg ,$data,$opts);
534 function runUpdateModulesData()
538 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
539 echo "Running jsonImportFromArray\n";
540 Pman_Core_UpdateDatabase::jsonImportFromArray($this->opts);
543 echo "Running updateData on modules\n";
547 $modules = array_reverse($this->modulesList());
549 // move 'project' one to the end...
551 foreach ($modules as $module){
552 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
553 if($module == 'Core' || !file_exists($file)){
558 $class = "Pman_{$module}_UpdateDatabase";
560 if(!method_exists($x, 'updateData')){
570 function updateDataEnums()
573 $enum = DB_DataObject::Factory('core_enum');
574 //DB_DAtaObject::debugLevel(1);
579 'name' => 'COMPTYPE',
580 'display_name' => 'Company Types',
581 'is_system_enum' => 1,
585 'display_name' => 'Owner',
586 'seqid' => 999, // last...
587 'is_system_enum' => 1,
594 'name' => 'HtmlEditor.font-family',
595 'display_name' => 'HTML Editor font families',
596 'is_system_enum' => 1,
599 'name' => 'Helvetica,Arial,sans-serif',
600 'display_name' => 'Helvetica',
605 'name' => 'Courier New',
606 'display_name' => 'Courier',
611 'display_name' => 'Tahoma',
615 'name' => 'Times New Roman,serif',
616 'display_name' => 'Times',
621 'display_name' => 'Verdana',
633 function updateDataGroups()
636 $groups = DB_DataObject::factory('groups');
637 $groups->initGroups();
639 $groups->initDatabase($this,array(
641 'name' => 'bcc-email', // group who are bcc'ed on all requests.
642 'type' => 0, // system
649 function updateDataCompanies()
652 // fix comptypes enums..
653 $c = DB_DataObject::Factory('Companies');
655 $c->selectAdd('distinct(comptype) as comptype');
656 $c->whereAdd("comptype != ''");
659 foreach($c->fetchAll('comptype') as $cts) {
663 $ctb[]= array( 'etype'=>'COMPTYPE', 'name' => $cts, 'display_name' => ucfirst(strtolower($cts)));
666 $c = DB_DataObject::Factory('core_enum');
669 //DB_DataObject::debugLevel(1);
671 $c = DB_DataObject::Factory('Companies');
675 comptype_id = (SELECT id FROM core_enum where etype='comptype' and name=Companies.comptype)
688 function updateData()
691 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
692 $this->updateDataEnums();
693 $this->updateDataGroups();
694 $this->updateDataCompanies();
696 $c = DB_DataObject::Factory('I18n');
703 function fixSequencesPgsql()
707 //DB_DataObject::debugLevel(1);
708 $cs = DB_DataObject::factory('core_enum');
712 CASE WHEN strpos(seq_name, '.') > 0 THEN
715 quote_ident(min(schema_name)) ||'.'|| quote_ident(min(seq_name))
718 ||' OWNED BY '|| quote_ident(min(schema_name)) || '.' ||
719 quote_ident(min(table_name)) ||'.'|| quote_ident(min(column_name)) ||';' as cmd
723 n.nspname AS schema_name,
724 c.relname AS table_name,
725 a.attname AS column_name,
726 regexp_replace(regexp_replace(d.adsrc, E'nextval\\\\(+[''\\\"]*', ''),E'[''\\\"]*::.*\$','') AS seq_name
728 JOIN pg_attribute a ON (c.oid=a.attrelid)
729 JOIN pg_attrdef d ON (a.attrelid=d.adrelid AND a.attnum=d.adnum)
730 JOIN pg_namespace n ON (c.relnamespace=n.oid)
731 WHERE has_schema_privilege(n.oid,'USAGE')
732 AND n.nspname NOT LIKE 'pg!_%' escape '!'
733 AND has_table_privilege(c.oid,'SELECT')
734 AND (NOT a.attisdropped)
735 AND d.adsrc ~ '^nextval'
739 CASE WHEN strpos(seq_name, '.') > 0 THEN
740 substring(seq_name, 1,strpos(seq_name,'.')-1)
745 GROUP BY seq_name HAVING count(*)=1
748 while ($cs->fetch()) {
751 foreach($cmds as $cmd) {
752 $cs = DB_DataObject::factory('core_enum');
756 $cs = DB_DataObject::factory('core_enum');
758 SELECT 'SELECT SETVAL(' ||
759 quote_literal(quote_ident(nspname) || '.' || quote_ident(S.relname)) ||
760 ', MAX(' || quote_ident(C.attname)|| ')::integer ) FROM ' || nspname || '.' || quote_ident(T.relname)|| ';' as cmd
766 WHERE S.relkind = 'S'
768 AND D.refobjid = T.oid
769 AND D.refobjid = C.attrelid
770 AND D.refobjsubid = C.attnum
771 AND NS.oid = T.relnamespace
775 while ($cs->fetch()) {
778 foreach($cmds as $cmd) {
779 $cs = DB_DataObject::factory('core_enum');