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 if (!empty($this->opts['only-module-sql']) && $m != $this->opts['only-module-sql']) {
264 echo "Importing SQL from module $m\n";
265 // if init has been called
267 if (!empty($this->opts['init'])) {
268 $this->importpgsqldir($dburl, $this->rootDir. "/Pman/$m/pgsql.init");
274 $fd = $this->rootDir. "/Pman/$m/DataObjects";
276 $this->importpgsqldir($dburl, $fd);
278 // new -- sql directory..
279 // new style will not support migrate ... they have to go into mysql-migrate.... directories..
280 // new style will not support pg.sql etc.. naming - that's what the direcotries are for..
282 $this->importpgsqldir($dburl, $this->rootDir. "/Pman/$m/sql");
283 $this->importpgsqldir($dburl, $this->rootDir. "/Pman/$m/pgsql");
287 if (!empty($this->opts['init']) && file_exists($this->rootDir. "/Pman/$m/pgsql.initdata")) {
288 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
290 $this->importpgsqldir($dburl, $this->rootDir. "/Pman/$m/pgsql.initdata");
291 $this->fixSequencesPgsql();
300 function importpgsqldir($url, $dir, $disable_triggers = false)
302 require_once 'System.php';
303 $cat = System::which('cat');
304 $psql = System::which('psql');
307 if (!empty($url['pass'])) {
308 putenv("PGPASSWORD=". $url['pass']);
312 ' -h ' . $url['host'] .
313 ' -U' . escapeshellarg($url['user']) .
314 ' ' . basename($url['path']);
317 echo $psql_cmd . "\n" ;
318 echo "scan : $dir\n";
319 foreach(glob($dir.'/*.sql') as $bfn) {
322 if (preg_match('/migrate/i', basename($bfn))) { // skip migration scripts at present..
325 if (preg_match('#\.[a-z]{2}\.sql#i', basename($bfn))
326 && !preg_match('#\.pg\.sql#i', basename($bfn))
327 ) { // skip migration scripts at present..
332 if (!preg_match('/pgsql/', basename($dir) )) {
333 if ( !preg_match('#\.pg\.sql$#', basename($bfn))) {
334 $fn = $this->convertToPG($bfn);
338 // files ending in .pg.sql are native postgres files.. ## depricated
341 $cmd = "$psql_cmd < " . escapeshellarg($fn ? $fn : $bfn) . ' 2>&1' ;
343 echo "$bfn: $cmd ". ($this->cli ? "\n" : "<BR>\n");
358 * simple regex based convert mysql to pgsql...
360 function convertToPG($src)
362 //echo "Convert $src\n";
364 $fn = $this->tempName('sql');
366 $ret = array( ); // pad it a bit.
367 $extra = array("", "" );
370 foreach(file($src) as $l) {
373 if (!strlen($l) || $l[0] == '#') {
377 if (preg_match('#create\s+table\s+([a-z0-9_]+)#i', $l, $m)) {
380 if (preg_match('#create\s+table\s+\`([a-z0-9_]+)\`#i', $l, $m)) {
381 $tbl = 'shop_' . strtolower($m[1]);
382 $l = preg_replace('#create\s+table\s+\`([a-z0-9_]+)\`#i', "CREATE TABLE {$tbl}", $l);
384 if (preg_match('#\`([a-z0-9_]+)\`#i', $l, $m) && !preg_match('#alter\s+table\s+#i', $l)) {
385 $l = preg_replace('#\`([a-z0-9_]+)\`#i', "{$m[1]}_name", $l);
388 if ($tbl && preg_match('#auto_increment#i', $l, $m)) {
389 $l = preg_replace('#auto_increment#i', "default nextval('{$tbl}_seq')", $l);
390 $extra[] = "create sequence {$tbl}_seq;";
394 if (preg_match('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', $l, $m)){
395 $l = preg_replace('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', "ALTER TABLE {$tbl}", $l);
398 // enum value -- use the text instead..
400 if ($tbl && preg_match('#([\w]+)\s+(enum\([\w|\W]+\))#i', $l, $m)) {
401 $l = preg_replace('#enum\([\w|\W]+\)#i', "TEXT", $l);
403 // ignore the alter enum
404 if ($tbl && preg_match('#alter\s+table\s+([\w|\W]+)\s+enum\([\w|\W]+\)#i', $l, $m)) {
408 // UNIQUE KEY .. ignore
409 if ($tbl && preg_match('#UNIQUE KEY#i', $l, $m)) {
410 $last = array_pop($ret);
411 $ret[] = trim($last, ",");
415 if ($tbl && preg_match('#RENAME\s+TO#i', $l, $m)) {
419 if ($tbl && preg_match('#change\s+column#i', $l, $m)) {
423 // INDEX lookup ..ignore
424 if ($tbl && preg_match('#INDEX lookup+([\w|\W]+)#i', $l, $m)) {
425 $last = array_pop($ret);
426 $ret[] = trim($last, ",");
431 // CREATE INDEX ..ignore
432 if (preg_match('#alter\s+table\s+([a-z0-9_]+)\s+add\s+index\s+#i', $l, $m)) {
433 // $l = "CREATE INDEX {$m[1]}_{$m[2]} ON {$m[1]} {$m[3]}";
438 $l = preg_replace('#int\([0-9]+\)#i', 'INT', $l);
440 $l = preg_replace('# datetime#i', ' TIMESTAMP WITHOUT TIME ZONE', $l);
441 $l = preg_replace('# blob#i', ' TEXT', $l);
442 $l = preg_replace('# longtext#i', ' TEXT', $l);
443 $l = preg_replace('# tinyint#i', ' INT', $l);
449 $ret = array_merge($extra,$ret);
450 // echo implode("\n", $ret); exit;
452 file_put_contents($fn, implode("\n", $ret));
458 function checkOpts($opts)
462 foreach($opts as $o=>$v) {
463 if (!preg_match('/^json-/', $o) || empty($v)) {
466 if (!file_exists($v)) {
467 die("File does not exist : OPTION --{$o} = {$v} \n");
471 $modules = array_reverse($this->modulesList());
473 // move 'project' one to the end...
475 foreach ($modules as $module){
476 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
477 if($module == 'Core' || !file_exists($file)){
481 $class = "Pman_{$module}_UpdateDatabase";
483 if(!method_exists($x, 'checkOpts')){
486 $x->checkOpts($opts);
490 static function jsonImportFromArray($opts)
492 foreach($opts as $o=>$v) {
493 if (!preg_match('/^json-/', $o) || empty($v)) {
496 $type = str_replace('_', '-', substr($o,6));
497 $data= json_decode(file_get_contents($file),true);
498 DB_DataObject::factory($type)->importFromArray($this,$data,$opts);
506 function runUpdateModulesData()
510 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
511 echo "Running jsonImportFromArray\n";
512 Pman_Core_UpdateDatabase::jsonImportFromArray($this->opts);
515 echo "Running updateData on modules\n";
519 $modules = array_reverse($this->modulesList());
521 // move 'project' one to the end...
523 foreach ($modules as $module){
524 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
525 if($module == 'Core' || !file_exists($file)){
530 $class = "Pman_{$module}_UpdateDatabase";
532 if(!method_exists($x, 'updateData')){
542 function updateDataEnums()
544 $enum = DB_DataObject::Factory('core_enum');
549 'name' => 'COMPTYPE',
550 'display_name' => 'Company Types',
551 'is_system_enum' => 1,
555 'display_name' => 'Owner',
556 'seqid' => 999, // last...
557 'is_system_enum' => 1,
564 'name' => 'HtmlEditor.font-family',
565 'display_name' => 'HTML Editor font families',
566 'is_system_enum' => 1,
569 'name' => 'Helvetica,Arial,sans-serif',
570 'display_name' => 'Helvetica',
575 'name' => 'Courier New',
576 'display_name' => 'Courier',
581 'display_name' => 'Tahoma',
585 'name' => 'Times New Roman,serif',
586 'display_name' => 'Times',
591 'display_name' => 'Verdana',
603 function updateDataGroups()
606 $groups = DB_DataObject::factory('groups');
607 $groups->initGroups();
609 $groups->initDatabase($this,array(
611 'name' => 'bcc-email', // group who are bcc'ed on all requests.
612 'type' => 0, // system
619 function updateDataCompanies()
622 // fix comptypes enums..
623 $c = DB_DataObject::Factory('Companies');
625 $c->selectAdd('distinct(comptype) as comptype');
626 $c->whereAdd("comptype != ''");
629 foreach($c->fetchAll('comptype') as $cts) {
633 $ctb[]= array( 'etype'=>'COMPTYPE', 'name' => $cts, 'display_name' => ucfirst(strtolower($cts)));
636 $c = DB_DataObject::Factory('core_enum');
639 //DB_DataObject::debugLevel(1);
641 $c = DB_DataObject::Factory('Companies');
645 comptype_id = (SELECT id FROM core_enum where etype='comptype' and name=Companies.comptype)
658 function updateData()
662 $this->updateDataEnums();
663 $this->updateDataGroups();
664 $this->updateDataCompanies();
666 $c = DB_DataObject::Factory('I18n');
673 function fixSequencesPgsql()
675 //DB_DataObject::debugLevel(1);
676 $cs = DB_DataObject::factory('core_enum');
678 SELECT 'ALTER SEQUENCE '|| quote_ident(min(schema_name)) ||'.'|| quote_ident(min(seq_name))
679 ||' OWNED BY '|| quote_ident(min(schema_name)) || '.' ||
680 quote_ident(min(table_name)) ||'.'|| quote_ident(min(column_name)) ||';' as cmd
684 n.nspname AS schema_name,
685 c.relname AS table_name,
686 a.attname AS column_name,
687 regexp_replace(regexp_replace(d.adsrc, E'nextval\\\\(+[''\"]*', ''),E'[''\"]*::.*\$','') AS seq_name
689 JOIN pg_attribute a ON (c.oid=a.attrelid)
690 JOIN pg_attrdef d ON (a.attrelid=d.adrelid AND a.attnum=d.adnum)
691 JOIN pg_namespace n ON (c.relnamespace=n.oid)
692 WHERE has_schema_privilege(n.oid,'USAGE')
693 AND n.nspname NOT LIKE 'pg!_%' escape '!'
694 AND has_table_privilege(c.oid,'SELECT')
695 AND (NOT a.attisdropped)
696 AND d.adsrc ~ '^nextval'
699 GROUP BY seq_name HAVING count(*)=1
702 while ($cs->fetch()) {
705 foreach($cmds as $cmd) {
706 $cs = DB_DataObject::factory('core_enum');
709 $cs = DB_DataObject::factory('core_enum');
711 SELECT 'SELECT SETVAL(' ||
712 quote_literal(quote_ident(nspname) || '.' || quote_ident(S.relname)) ||
713 ', MAX(' || quote_ident(C.attname)|| ') ) FROM ' || nspname || '.' || quote_ident(T.relname)|| ';' as cmd
719 WHERE S.relkind = 'S'
721 AND D.refobjid = T.oid
722 AND D.refobjid = C.attrelid
723 AND D.refobjsubid = C.attnum
724 AND NS.oid = T.relnamespace
728 while ($cs->fetch()) {
731 foreach($cmds as $cmd) {
732 $cs = DB_DataObject::factory('core_enum');