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)
124 //$this->fixSequencesPgsql();exit;
127 // ask all the modules to verify the opts
129 $this->checkOpts($opts);
132 if (!empty($opts['add-company'])) {
133 DB_DataObject::factory('companies')->initCompanies($this, $opts);
136 if (empty($opts['data-only'])) {
139 if (!empty($opts['only-module-sql'])) {
143 $this->runUpdateModulesData();
150 * imports SQL files from all DataObjects directories....
152 * except any matching /migrate/
157 $ff = HTML_Flexyframework::get();
159 $url = parse_url($ff->DB_DataObject['database']);
161 $this->{'import' . $url['scheme']}($url);
166 * mysql - does not support conversions.
172 function importmysqldir($dburl, $dir)
174 echo "Import MYSQL :: $dir\n";
177 require_once 'System.php';
178 $cat = System::which('cat');
179 $mysql = System::which('mysql');
183 $mysql_cmd = $mysql .
184 ' -h ' . $dburl['host'] .
185 ' -u' . escapeshellarg($dburl['user']) .
186 (!empty($dburl['pass']) ? ' -p' . escapeshellarg($dburl['pass']) : '') .
187 ' ' . basename($dburl['path']);
188 //echo $mysql_cmd . "\n" ;
191 foreach(glob($dir.'/*.sql') as $fn) {
194 if (preg_match('/migrate/i', basename($fn))) { // skip migration scripts at present..
197 // .my.sql but not .pg.sql
198 if (preg_match('#\.[a-z]{2}\.sql#i', basename($fn))
199 && !preg_match('#\.my\.sql#i', basename($fn))
200 ) { // skip migration scripts at present..
203 if (!strlen(trim($fn))) {
207 $cmd = "$mysql_cmd -f < " . escapeshellarg($fn) ;
209 echo basename($dir).'/'. basename($fn) . '::' . $cmd. ($this->cli ? "\n" : "<BR>\n");
222 function importmysql($dburl)
225 // hide stuff for web..
226 $ar = $this->modulesList();
230 // old -- DAtaObjects/*.sql
234 if (!empty($this->opts['only-module-sql']) && $m != $this->opts['only-module-sql']) {
238 $fd = $this->rootDir. "/Pman/$m/DataObjects";
240 $this->importmysqldir($dburl, $fd);
242 // new -- sql directory..
243 // new style will not support migrate ... they have to go into mysql-migrate.... directories..
244 // new style will not support pg.sql etc.. naming - that's what the direcotries are for..
246 $this->importmysqldir($dburl, $this->rootDir. "/Pman/$m/sql");
247 $this->importmysqldir($dburl, $this->rootDir. "/Pman/$m/mysql");
256 * postgresql import..
258 function importpgsql($dburl)
261 // hide stuff for web..
266 $ar = $this->modulesList();
270 echo "Importing SQL from module $m\n";
271 if (!empty($this->opts['only-module-sql']) && $m != $this->opts['only-module-sql']) {
274 echo "Importing SQL from module $m\n";
275 // if init has been called
277 if (!empty($this->opts['init'])) {
278 $this->importpgsqldir($dburl, $this->rootDir. "/Pman/$m/pgsql.init");
284 $fd = $this->rootDir. "/Pman/$m/DataObjects";
286 $this->importpgsqldir($dburl, $fd);
288 // new -- sql directory..
289 // new style will not support migrate ... they have to go into mysql-migrate.... directories..
290 // new style will not support pg.sql etc.. naming - that's what the direcotries are for..
292 $this->importpgsqldir($dburl, $this->rootDir. "/Pman/$m/sql");
293 $this->importpgsqldir($dburl, $this->rootDir. "/Pman/$m/pgsql");
297 if (!empty($this->opts['init']) && file_exists($this->rootDir. "/Pman/$m/pgsql.initdata")) {
298 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
300 $this->importpgsqldir($dburl, $this->rootDir. "/Pman/$m/pgsql.initdata");
301 $this->fixSequencesPgsql();
310 function importpgsqldir($url, $dir, $disable_triggers = false)
312 require_once 'System.php';
313 $cat = System::which('cat');
314 $psql = System::which('psql');
317 if (!empty($url['pass'])) {
318 putenv("PGPASSWORD=". $url['pass']);
322 ' -h ' . $url['host'] .
323 ' -U' . escapeshellarg($url['user']) .
324 ' ' . basename($url['path']);
327 echo $psql_cmd . "\n" ;
328 echo "scan : $dir\n";
329 foreach(glob($dir.'/*.sql') as $bfn) {
332 if (preg_match('/migrate/i', basename($bfn))) { // skip migration scripts at present..
335 if (preg_match('#\.[a-z]{2}\.sql#i', basename($bfn))
336 && !preg_match('#\.pg\.sql#i', basename($bfn))
337 ) { // skip migration scripts at present..
342 if (!preg_match('/pgsql/', basename($dir) )) {
343 if ( !preg_match('#\.pg\.sql$#', basename($bfn))) {
344 $fn = $this->convertToPG($bfn);
348 // files ending in .pg.sql are native postgres files.. ## depricated
351 $cmd = "$psql_cmd < " . escapeshellarg($fn ? $fn : $bfn) . ' 2>&1' ;
353 echo "$bfn: $cmd ". ($this->cli ? "\n" : "<BR>\n");
368 * simple regex based convert mysql to pgsql...
370 function convertToPG($src)
372 //echo "Convert $src\n";
374 $fn = $this->tempName('sql');
376 $ret = array( ); // pad it a bit.
377 $extra = array("", "" );
380 foreach(file($src) as $l) {
383 if (!strlen($l) || $l[0] == '#') {
387 if (preg_match('#create\s+table\s+([a-z0-9_]+)#i', $l, $m)) {
390 if (preg_match('#create\s+table\s+\`([a-z0-9_]+)\`#i', $l, $m)) {
391 $tbl = 'shop_' . strtolower($m[1]);
392 $l = preg_replace('#create\s+table\s+\`([a-z0-9_]+)\`#i', "CREATE TABLE {$tbl}", $l);
394 if (preg_match('#\`([a-z0-9_]+)\`#i', $l, $m) && !preg_match('#alter\s+table\s+#i', $l)) {
395 $l = preg_replace('#\`([a-z0-9_]+)\`#i', "{$m[1]}_name", $l);
398 if ($tbl && preg_match('#auto_increment#i', $l, $m)) {
399 $l = preg_replace('#auto_increment#i', "default nextval('{$tbl}_seq')", $l);
400 $extra[] = "create sequence {$tbl}_seq;";
404 if (preg_match('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', $l, $m)){
405 $l = preg_replace('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', "ALTER TABLE {$tbl}", $l);
408 // enum value -- use the text instead..
410 if ($tbl && preg_match('#([\w]+)\s+(enum\([\w|\W]+\))#i', $l, $m)) {
411 $l = preg_replace('#enum\([\w|\W]+\)#i', "TEXT", $l);
413 // ignore the alter enum
414 if ($tbl && preg_match('#alter\s+table\s+([\w|\W]+)\s+enum\([\w|\W]+\)#i', $l, $m)) {
418 // UNIQUE KEY .. ignore
419 if ($tbl && preg_match('#UNIQUE KEY#i', $l, $m)) {
420 $last = array_pop($ret);
421 $ret[] = trim($last, ",");
425 if ($tbl && preg_match('#RENAME\s+TO#i', $l, $m)) {
429 if ($tbl && preg_match('#change\s+column#i', $l, $m)) {
433 // INDEX lookup ..ignore
434 if ($tbl && preg_match('#INDEX lookup+([\w|\W]+)#i', $l, $m)) {
435 $last = array_pop($ret);
436 $ret[] = trim($last, ",");
441 // CREATE INDEX ..ignore
442 if (preg_match('#alter\s+table\s+([a-z0-9_]+)\s+add\s+index\s+#i', $l, $m)) {
443 // $l = "CREATE INDEX {$m[1]}_{$m[2]} ON {$m[1]} {$m[3]}";
448 $l = preg_replace('#int\([0-9]+\)#i', 'INT', $l);
450 $l = preg_replace('# datetime#i', ' TIMESTAMP WITHOUT TIME ZONE', $l);
451 $l = preg_replace('# blob#i', ' TEXT', $l);
452 $l = preg_replace('# longtext#i', ' TEXT', $l);
453 $l = preg_replace('# tinyint#i', ' INT', $l);
459 $ret = array_merge($extra,$ret);
460 // echo implode("\n", $ret); exit;
462 file_put_contents($fn, implode("\n", $ret));
468 function checkOpts($opts)
472 foreach($opts as $o=>$v) {
473 if (!preg_match('/^json-/', $o) || empty($v)) {
476 if (!file_exists($v)) {
477 die("File does not exist : OPTION --{$o} = {$v} \n");
481 $modules = array_reverse($this->modulesList());
483 // move 'project' one to the end...
485 foreach ($modules as $module){
486 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
487 if($module == 'Core' || !file_exists($file)){
491 $class = "Pman_{$module}_UpdateDatabase";
493 if(!method_exists($x, 'checkOpts')){
496 $x->checkOpts($opts);
500 static function jsonImportFromArray($opts)
502 foreach($opts as $o=>$v) {
503 if (!preg_match('/^json-/', $o) || empty($v)) {
506 $type = str_replace('_', '-', substr($o,6));
507 $data= json_decode(file_get_contents($file),true);
508 DB_DataObject::factory($type)->importFromArray($this,$data,$opts);
516 function runUpdateModulesData()
520 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
521 echo "Running jsonImportFromArray\n";
522 Pman_Core_UpdateDatabase::jsonImportFromArray($this->opts);
525 echo "Running updateData on modules\n";
529 $modules = array_reverse($this->modulesList());
531 // move 'project' one to the end...
533 foreach ($modules as $module){
534 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
535 if($module == 'Core' || !file_exists($file)){
540 $class = "Pman_{$module}_UpdateDatabase";
542 if(!method_exists($x, 'updateData')){
552 function updateDataEnums()
554 $enum = DB_DataObject::Factory('core_enum');
559 'name' => 'COMPTYPE',
560 'display_name' => 'Company Types',
561 'is_system_enum' => 1,
565 'display_name' => 'Owner',
566 'seqid' => 999, // last...
567 'is_system_enum' => 1,
574 'name' => 'HtmlEditor.font-family',
575 'display_name' => 'HTML Editor font families',
576 'is_system_enum' => 1,
579 'name' => 'Helvetica,Arial,sans-serif',
580 'display_name' => 'Helvetica',
585 'name' => 'Courier New',
586 'display_name' => 'Courier',
591 'display_name' => 'Tahoma',
595 'name' => 'Times New Roman,serif',
596 'display_name' => 'Times',
601 'display_name' => 'Verdana',
613 function updateDataGroups()
616 $groups = DB_DataObject::factory('groups');
617 $groups->initGroups();
619 $groups->initDatabase($this,array(
621 'name' => 'bcc-email', // group who are bcc'ed on all requests.
622 'type' => 0, // system
629 function updateDataCompanies()
632 // fix comptypes enums..
633 $c = DB_DataObject::Factory('Companies');
635 $c->selectAdd('distinct(comptype) as comptype');
636 $c->whereAdd("comptype != ''");
639 foreach($c->fetchAll('comptype') as $cts) {
643 $ctb[]= array( 'etype'=>'COMPTYPE', 'name' => $cts, 'display_name' => ucfirst(strtolower($cts)));
646 $c = DB_DataObject::Factory('core_enum');
649 //DB_DataObject::debugLevel(1);
651 $c = DB_DataObject::Factory('Companies');
655 comptype_id = (SELECT id FROM core_enum where etype='comptype' and name=Companies.comptype)
668 function updateData()
672 $this->updateDataEnums();
673 $this->updateDataGroups();
674 $this->updateDataCompanies();
676 $c = DB_DataObject::Factory('I18n');
683 function fixSequencesPgsql()
685 //DB_DataObject::debugLevel(1);
686 $cs = DB_DataObject::factory('core_enum');
688 SELECT 'ALTER SEQUENCE '|| quote_ident(min(schema_name)) ||'.'|| quote_ident(min(seq_name))
689 ||' OWNED BY '|| quote_ident(min(schema_name)) || '.' ||
690 quote_ident(min(table_name)) ||'.'|| quote_ident(min(column_name)) ||';' as cmd
694 n.nspname AS schema_name,
695 c.relname AS table_name,
696 a.attname AS column_name,
697 regexp_replace(regexp_replace(d.adsrc, E'nextval\\\\(+[''\"]*', ''),E'[''\"]*::.*\$','') AS seq_name
699 JOIN pg_attribute a ON (c.oid=a.attrelid)
700 JOIN pg_attrdef d ON (a.attrelid=d.adrelid AND a.attnum=d.adnum)
701 JOIN pg_namespace n ON (c.relnamespace=n.oid)
702 WHERE has_schema_privilege(n.oid,'USAGE')
703 AND n.nspname NOT LIKE 'pg!_%' escape '!'
704 AND has_table_privilege(c.oid,'SELECT')
705 AND (NOT a.attisdropped)
706 AND d.adsrc ~ '^nextval'
709 GROUP BY seq_name HAVING count(*)=1
712 while ($cs->fetch()) {
715 foreach($cmds as $cmd) {
716 $cs = DB_DataObject::factory('core_enum');
719 $cs = DB_DataObject::factory('core_enum');
721 SELECT 'SELECT SETVAL(' ||
722 quote_literal(quote_ident(nspname) || '.' || quote_ident(S.relname)) ||
723 ', MAX(' || quote_ident(C.attname)|| ') ) FROM ' || nspname || '.' || quote_ident(T.relname)|| ';' as cmd
729 WHERE S.relkind = 'S'
731 AND D.refobjid = T.oid
732 AND D.refobjid = C.attrelid
733 AND D.refobjsubid = C.attnum
734 AND NS.oid = T.relnamespace
738 while ($cs->fetch()) {
741 foreach($cmds as $cmd) {
742 $cs = DB_DataObject::factory('core_enum');