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)',
29 'add-company' => array(
30 'desc' => 'add a company name of the company',
36 'add-company-with-type' => array(
37 'desc' => 'the type of company (default OWNER)',
44 'desc' => 'Initialize the database (pg only supported)',
50 'only-module-sql' => array(
51 'desc' => 'Only run sql import on this modules - eg. Core',
57 'json-person' => array(
58 'desc' => 'Person JSON file',
66 static function cli_opts()
69 $ret = self::$cli_opts;
70 $ff = HTML_FlexyFramework::get();
72 $mods = $a->modulesList();
73 foreach($mods as $m) {
75 $fd = $ff->rootDir. "/Pman/$m/UpdateDatabase.php";
76 if (!file_exists($fd)) {
82 $cls = new ReflectionClass('Pman_'. $m . '_UpdateDatabase');
84 $ret = array_merge($ret, $cls->getStaticPropertyValue('cli_opts'));
99 $ff = HTML_FlexyFramework::get();
100 if (!empty($ff->cli)) {
105 parent::getAuth(); // load company!
106 $au = $this->getAuthUser();
107 if (!$au || $au->company()->comptype != 'OWNER') {
108 $this->jerr("Not authenticated", array('authFailure' => true));
110 $this->authUser = $au;
114 function get($args, $opts)
116 //$this->fixSequencesPgsql();exit;
119 // ask all the modules to verify the opts
121 $this->checkOpts($opts);
124 if (!empty($opts['add-company'])) {
125 DB_DataObject::factory('companies')->initCompanies($this, $opts);
130 if (!empty($opts['only-module-sql'])) {
134 $this->runUpdateModulesData();
141 * imports SQL files from all DataObjects directories....
143 * except any matching /migrate/
148 $ff = HTML_Flexyframework::get();
150 $url = parse_url($ff->DB_DataObject['database']);
152 $this->{'import' . $url['scheme']}($url);
157 * mysql - does not support conversions.
163 function importmysqldir($dburl, $dir)
165 echo "Import MYSQL :: $dir\n";
168 require_once 'System.php';
169 $cat = System::which('cat');
170 $mysql = System::which('mysql');
174 $mysql_cmd = $mysql .
175 ' -h ' . $dburl['host'] .
176 ' -u' . escapeshellarg($dburl['user']) .
177 (!empty($dburl['pass']) ? ' -p' . escapeshellarg($dburl['pass']) : '') .
178 ' ' . basename($dburl['path']);
179 //echo $mysql_cmd . "\n" ;
182 foreach(glob($dir.'/*.sql') as $fn) {
185 if (preg_match('/migrate/i', basename($fn))) { // skip migration scripts at present..
188 // .my.sql but not .pg.sql
189 if (preg_match('#\.[a-z]{2}\.sql#i', basename($fn))
190 && !preg_match('#\.my\.sql#i', basename($fn))
191 ) { // skip migration scripts at present..
194 if (!strlen(trim($fn))) {
198 $cmd = "$mysql_cmd -f < " . escapeshellarg($fn) ;
200 echo basename($dir).'/'. basename($fn) . '::' . $cmd. ($this->cli ? "\n" : "<BR>\n");
213 function importmysql($dburl)
216 // hide stuff for web..
217 $ar = $this->modulesList();
221 // old -- DAtaObjects/*.sql
225 if (!empty($this->opts['only-module-sql']) && $m != $this->opts['only-module-sql']) {
229 $fd = $this->rootDir. "/Pman/$m/DataObjects";
231 $this->importmysqldir($dburl, $fd);
233 // new -- sql directory..
234 // new style will not support migrate ... they have to go into mysql-migrate.... directories..
235 // new style will not support pg.sql etc.. naming - that's what the direcotries are for..
237 $this->importmysqldir($dburl, $this->rootDir. "/Pman/$m/sql");
238 $this->importmysqldir($dburl, $this->rootDir. "/Pman/$m/mysql");
247 * postgresql import..
249 function importpgsql($dburl)
252 // hide stuff for web..
257 $ar = $this->modulesList();
261 echo "Importing SQL from module $m\n";
262 if (!empty($this->opts['only-module-sql']) && $m != $this->opts['only-module-sql']) {
265 echo "Importing SQL from module $m\n";
266 // if init has been called
268 if (!empty($this->opts['init'])) {
269 $this->importpgsqldir($dburl, $this->rootDir. "/Pman/$m/pgsql.init");
275 $fd = $this->rootDir. "/Pman/$m/DataObjects";
277 $this->importpgsqldir($dburl, $fd);
279 // new -- sql directory..
280 // new style will not support migrate ... they have to go into mysql-migrate.... directories..
281 // new style will not support pg.sql etc.. naming - that's what the direcotries are for..
283 $this->importpgsqldir($dburl, $this->rootDir. "/Pman/$m/sql");
284 $this->importpgsqldir($dburl, $this->rootDir. "/Pman/$m/pgsql");
288 if (!empty($this->opts['init']) && file_exists($this->rootDir. "/Pman/$m/pgsql.initdata")) {
289 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
291 $this->importpgsqldir($dburl, $this->rootDir. "/Pman/$m/pgsql.initdata");
292 $this->fixSequencesPgsql();
301 function importpgsqldir($url, $dir, $disable_triggers = false)
303 require_once 'System.php';
304 $cat = System::which('cat');
305 $psql = System::which('psql');
308 if (!empty($url['pass'])) {
309 putenv("PGPASSWORD=". $url['pass']);
313 ' -h ' . $url['host'] .
314 ' -U' . escapeshellarg($url['user']) .
315 ' ' . basename($url['path']);
318 echo $psql_cmd . "\n" ;
319 echo "scan : $dir\n";
320 foreach(glob($dir.'/*.sql') as $bfn) {
323 if (preg_match('/migrate/i', basename($bfn))) { // skip migration scripts at present..
326 if (preg_match('#\.[a-z]{2}\.sql#i', basename($bfn))
327 && !preg_match('#\.pg\.sql#i', basename($bfn))
328 ) { // skip migration scripts at present..
333 if (!preg_match('/pgsql/', basename($dir) )) {
334 if ( !preg_match('#\.pg\.sql$#', basename($bfn))) {
335 $fn = $this->convertToPG($bfn);
339 // files ending in .pg.sql are native postgres files.. ## depricated
342 $cmd = "$psql_cmd < " . escapeshellarg($fn ? $fn : $bfn) . ' 2>&1' ;
344 echo "$bfn: $cmd ". ($this->cli ? "\n" : "<BR>\n");
359 * simple regex based convert mysql to pgsql...
361 function convertToPG($src)
363 //echo "Convert $src\n";
365 $fn = $this->tempName('sql');
367 $ret = array( ); // pad it a bit.
368 $extra = array("", "" );
371 foreach(file($src) as $l) {
374 if (!strlen($l) || $l[0] == '#') {
378 if (preg_match('#create\s+table\s+([a-z0-9_]+)#i', $l, $m)) {
381 if (preg_match('#create\s+table\s+\`([a-z0-9_]+)\`#i', $l, $m)) {
382 $tbl = 'shop_' . strtolower($m[1]);
383 $l = preg_replace('#create\s+table\s+\`([a-z0-9_]+)\`#i', "CREATE TABLE {$tbl}", $l);
385 if (preg_match('#\`([a-z0-9_]+)\`#i', $l, $m) && !preg_match('#alter\s+table\s+#i', $l)) {
386 $l = preg_replace('#\`([a-z0-9_]+)\`#i', "{$m[1]}_name", $l);
389 if ($tbl && preg_match('#auto_increment#i', $l, $m)) {
390 $l = preg_replace('#auto_increment#i', "default nextval('{$tbl}_seq')", $l);
391 $extra[] = "create sequence {$tbl}_seq;";
395 if (preg_match('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', $l, $m)){
396 $l = preg_replace('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', "ALTER TABLE {$tbl}", $l);
399 // enum value -- use the text instead..
401 if ($tbl && preg_match('#([\w]+)\s+(enum\([\w|\W]+\))#i', $l, $m)) {
402 $l = preg_replace('#enum\([\w|\W]+\)#i', "TEXT", $l);
404 // ignore the alter enum
405 if ($tbl && preg_match('#alter\s+table\s+([\w|\W]+)\s+enum\([\w|\W]+\)#i', $l, $m)) {
409 // UNIQUE KEY .. ignore
410 if ($tbl && preg_match('#UNIQUE KEY#i', $l, $m)) {
411 $last = array_pop($ret);
412 $ret[] = trim($last, ",");
416 if ($tbl && preg_match('#RENAME\s+TO#i', $l, $m)) {
420 if ($tbl && preg_match('#change\s+column#i', $l, $m)) {
424 // INDEX lookup ..ignore
425 if ($tbl && preg_match('#INDEX lookup+([\w|\W]+)#i', $l, $m)) {
426 $last = array_pop($ret);
427 $ret[] = trim($last, ",");
432 // CREATE INDEX ..ignore
433 if (preg_match('#alter\s+table\s+([a-z0-9_]+)\s+add\s+index\s+#i', $l, $m)) {
434 // $l = "CREATE INDEX {$m[1]}_{$m[2]} ON {$m[1]} {$m[3]}";
439 $l = preg_replace('#int\([0-9]+\)#i', 'INT', $l);
441 $l = preg_replace('# datetime#i', ' TIMESTAMP WITHOUT TIME ZONE', $l);
442 $l = preg_replace('# blob#i', ' TEXT', $l);
443 $l = preg_replace('# longtext#i', ' TEXT', $l);
444 $l = preg_replace('# tinyint#i', ' INT', $l);
450 $ret = array_merge($extra,$ret);
451 // echo implode("\n", $ret); exit;
453 file_put_contents($fn, implode("\n", $ret));
459 function checkOpts($opts)
463 foreach($opts as $o=>$v) {
464 if (!preg_match('/^json-/', $o) || empty($v)) {
467 if (!file_exists($v)) {
468 die("File does not exist : OPTION --{$o} = {$v} \n");
472 $modules = array_reverse($this->modulesList());
474 // move 'project' one to the end...
476 foreach ($modules as $module){
477 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
478 if($module == 'Core' || !file_exists($file)){
482 $class = "Pman_{$module}_UpdateDatabase";
484 if(!method_exists($x, 'checkOpts')){
487 $x->checkOpts($opts);
491 static function jsonImportFromArray($opts)
493 foreach($opts as $o=>$v) {
494 if (!preg_match('/^json-/', $o) || empty($v)) {
497 $type = str_replace('_', '-', substr($o,6));
498 $data= json_decode(file_get_contents($file),true);
499 DB_DataObject::factory($type)->importFromArray($this,$data,$opts);
507 function runUpdateModulesData()
511 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
512 echo "Running jsonImportFromArray\n";
513 Pman_Core_UpdateDatabase::jsonImportFromArray($this->opts);
516 echo "Running updateData on modules\n";
520 $modules = array_reverse($this->modulesList());
522 // move 'project' one to the end...
524 foreach ($modules as $module){
525 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
526 if($module == 'Core' || !file_exists($file)){
531 $class = "Pman_{$module}_UpdateDatabase";
533 if(!method_exists($x, 'updateData')){
543 function updateDataEnums()
545 $enum = DB_DataObject::Factory('core_enum');
550 'name' => 'COMPTYPE',
551 'display_name' => 'Company Types',
552 'is_system_enum' => 1,
556 'display_name' => 'Owner',
557 'seqid' => 999, // last...
558 'is_system_enum' => 1,
565 'name' => 'HtmlEditor.font-family',
566 'display_name' => 'HTML Editor font families',
567 'is_system_enum' => 1,
570 'name' => 'Helvetica,Arial,sans-serif',
571 'display_name' => 'Helvetica',
576 'name' => 'Courier New',
577 'display_name' => 'Courier',
582 'display_name' => 'Tahoma',
586 'name' => 'Times New Roman,serif',
587 'display_name' => 'Times',
592 'display_name' => 'Verdana',
604 function updateDataGroups()
607 $groups = DB_DataObject::factory('groups');
608 $groups->initGroups();
610 $groups->initDatabase($this,array(
612 'name' => 'bcc-email', // group who are bcc'ed on all requests.
613 'type' => 0, // system
620 function updateDataCompanies()
623 // fix comptypes enums..
624 $c = DB_DataObject::Factory('Companies');
626 $c->selectAdd('distinct(comptype) as comptype');
627 $c->whereAdd("comptype != ''");
630 foreach($c->fetchAll('comptype') as $cts) {
634 $ctb[]= array( 'etype'=>'COMPTYPE', 'name' => $cts, 'display_name' => ucfirst(strtolower($cts)));
637 $c = DB_DataObject::Factory('core_enum');
640 //DB_DataObject::debugLevel(1);
642 $c = DB_DataObject::Factory('Companies');
646 comptype_id = (SELECT id FROM core_enum where etype='comptype' and name=Companies.comptype)
659 function updateData()
663 $this->updateDataEnums();
664 $this->updateDataGroups();
665 $this->updateDataCompanies();
667 $c = DB_DataObject::Factory('I18n');
674 function fixSequencesPgsql()
676 //DB_DataObject::debugLevel(1);
677 $cs = DB_DataObject::factory('core_enum');
679 SELECT 'ALTER SEQUENCE '|| quote_ident(min(schema_name)) ||'.'|| quote_ident(min(seq_name))
680 ||' OWNED BY '|| quote_ident(min(schema_name)) || '.' ||
681 quote_ident(min(table_name)) ||'.'|| quote_ident(min(column_name)) ||';' as cmd
685 n.nspname AS schema_name,
686 c.relname AS table_name,
687 a.attname AS column_name,
688 regexp_replace(regexp_replace(d.adsrc, E'nextval\\\\(+[''\"]*', ''),E'[''\"]*::.*\$','') AS seq_name
690 JOIN pg_attribute a ON (c.oid=a.attrelid)
691 JOIN pg_attrdef d ON (a.attrelid=d.adrelid AND a.attnum=d.adnum)
692 JOIN pg_namespace n ON (c.relnamespace=n.oid)
693 WHERE has_schema_privilege(n.oid,'USAGE')
694 AND n.nspname NOT LIKE 'pg!_%' escape '!'
695 AND has_table_privilege(c.oid,'SELECT')
696 AND (NOT a.attisdropped)
697 AND d.adsrc ~ '^nextval'
700 GROUP BY seq_name HAVING count(*)=1
703 while ($cs->fetch()) {
706 foreach($cmds as $cmd) {
707 $cs = DB_DataObject::factory('core_enum');
710 $cs = DB_DataObject::factory('core_enum');
712 SELECT 'SELECT SETVAL(' ||
713 quote_literal(quote_ident(nspname) || '.' || quote_ident(S.relname)) ||
714 ', MAX(' || quote_ident(C.attname)|| ') ) FROM ' || nspname || '.' || quote_ident(T.relname)|| ';' as cmd
720 WHERE S.relkind = 'S'
722 AND D.refobjid = T.oid
723 AND D.refobjid = C.attrelid
724 AND D.refobjsubid = C.attnum
725 AND NS.oid = T.relnamespace
729 while ($cs->fetch()) {
732 foreach($cmds as $cmd) {
733 $cs = DB_DataObject::factory('core_enum');