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 $fd = $this->rootDir. "/Pman/$m/DataObjects";
227 $this->importmysqldir($dburl, $fd);
229 // new -- sql directory..
230 // new style will not support migrate ... they have to go into mysql-migrate.... directories..
231 // new style will not support pg.sql etc.. naming - that's what the direcotries are for..
233 $this->importmysqldir($dburl, $this->rootDir. "/Pman/$m/sql");
234 $this->importmysqldir($dburl, $this->rootDir. "/Pman/$m/mysql");
243 * postgresql import..
245 function importpgsql($dburl)
248 // hide stuff for web..
253 $ar = $this->modulesList();
257 // if init has been called
259 if (!empty($this->opts['init'])) {
260 $this->importpgsqldir($dburl, $this->rootDir. "/Pman/$m/pgsql.init");
266 $fd = $this->rootDir. "/Pman/$m/DataObjects";
268 $this->importpgsqldir($dburl, $fd);
270 // new -- sql directory..
271 // new style will not support migrate ... they have to go into mysql-migrate.... directories..
272 // new style will not support pg.sql etc.. naming - that's what the direcotries are for..
274 $this->importpgsqldir($dburl, $this->rootDir. "/Pman/$m/sql");
275 $this->importpgsqldir($dburl, $this->rootDir. "/Pman/$m/pgsql");
279 if (!empty($this->opts['init']) && file_exists($this->rootDir. "/Pman/$m/pgsql.initdata")) {
280 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
282 $this->importpgsqldir($dburl, $this->rootDir. "/Pman/$m/pgsql.initdata");
283 $this->fixSequencesPgsql();
292 function importpgsqldir($url, $dir, $disable_triggers = false)
294 require_once 'System.php';
295 $cat = System::which('cat');
296 $psql = System::which('psql');
299 if (!empty($url['pass'])) {
300 putenv("PGPASSWORD=". $url['pass']);
304 ' -h ' . $url['host'] .
305 ' -U' . escapeshellarg($url['user']) .
306 ' ' . basename($url['path']);
309 echo $psql_cmd . "\n" ;
310 echo "scan : $dir\n";
311 foreach(glob($dir.'/*.sql') as $bfn) {
314 if (preg_match('/migrate/i', basename($bfn))) { // skip migration scripts at present..
317 if (preg_match('#\.[a-z]{2}\.sql#i', basename($bfn))
318 && !preg_match('#\.pg\.sql#i', basename($bfn))
319 ) { // skip migration scripts at present..
324 if (!preg_match('/pgsql/', basename($dir) )) {
325 if ( !preg_match('#\.pg\.sql$#', basename($bfn))) {
326 $fn = $this->convertToPG($bfn);
330 // files ending in .pg.sql are native postgres files.. ## depricated
333 $cmd = "$psql_cmd < " . escapeshellarg($fn ? $fn : $bfn) . ' 2>&1' ;
335 echo "$bfn: $cmd ". ($this->cli ? "\n" : "<BR>\n");
350 * simple regex based convert mysql to pgsql...
352 function convertToPG($src)
354 //echo "Convert $src\n";
356 $fn = $this->tempName('sql');
358 $ret = array( ); // pad it a bit.
359 $extra = array("", "" );
362 foreach(file($src) as $l) {
365 if (!strlen($l) || $l[0] == '#') {
369 if (preg_match('#create\s+table\s+([a-z0-9_]+)#i', $l, $m)) {
372 if (preg_match('#create\s+table\s+\`([a-z0-9_]+)\`#i', $l, $m)) {
373 $tbl = 'shop_' . strtolower($m[1]);
374 $l = preg_replace('#create\s+table\s+\`([a-z0-9_]+)\`#i', "CREATE TABLE {$tbl}", $l);
376 if (preg_match('#\`([a-z0-9_]+)\`#i', $l, $m) && !preg_match('#alter\s+table\s+#i', $l)) {
377 $l = preg_replace('#\`([a-z0-9_]+)\`#i', "{$m[1]}_name", $l);
380 if ($tbl && preg_match('#auto_increment#i', $l, $m)) {
381 $l = preg_replace('#auto_increment#i', "default nextval('{$tbl}_seq')", $l);
382 $extra[] = "create sequence {$tbl}_seq;";
386 if (preg_match('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', $l, $m)){
387 $l = preg_replace('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', "ALTER TABLE {$tbl}", $l);
390 // enum value -- use the text instead..
392 if ($tbl && preg_match('#([\w]+)\s+(enum\([\w|\W]+\))#i', $l, $m)) {
393 $l = preg_replace('#enum\([\w|\W]+\)#i', "TEXT", $l);
395 // ignore the alter enum
396 if ($tbl && preg_match('#alter\s+table\s+([\w|\W]+)\s+enum\([\w|\W]+\)#i', $l, $m)) {
400 // UNIQUE KEY .. ignore
401 if ($tbl && preg_match('#UNIQUE KEY#i', $l, $m)) {
402 $last = array_pop($ret);
403 $ret[] = trim($last, ",");
407 if ($tbl && preg_match('#RENAME\s+TO#i', $l, $m)) {
411 if ($tbl && preg_match('#change\s+column#i', $l, $m)) {
415 // INDEX lookup ..ignore
416 if ($tbl && preg_match('#INDEX lookup+([\w|\W]+)#i', $l, $m)) {
417 $last = array_pop($ret);
418 $ret[] = trim($last, ",");
423 // CREATE INDEX ..ignore
424 if (preg_match('#alter\s+table\s+([a-z0-9_]+)\s+add\s+index\s+#i', $l, $m)) {
425 // $l = "CREATE INDEX {$m[1]}_{$m[2]} ON {$m[1]} {$m[3]}";
430 $l = preg_replace('#int\([0-9]+\)#i', 'INT', $l);
432 $l = preg_replace('# datetime#i', ' TIMESTAMP WITHOUT TIME ZONE', $l);
433 $l = preg_replace('# blob#i', ' TEXT', $l);
434 $l = preg_replace('# longtext#i', ' TEXT', $l);
435 $l = preg_replace('# tinyint#i', ' INT', $l);
441 $ret = array_merge($extra,$ret);
442 // echo implode("\n", $ret); exit;
444 file_put_contents($fn, implode("\n", $ret));
450 function checkOpts($opts)
454 foreach($opts as $o=>$v) {
455 if (!preg_match('/^json-/', $o) || empty($v)) {
458 if (!file_exists($v)) {
459 die("File does not exist : OPTION --{$o} = {$v} \n");
463 $modules = array_reverse($this->modulesList());
465 // move 'project' one to the end...
467 foreach ($modules as $module){
468 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
469 if($module == 'Core' || !file_exists($file)){
473 $class = "Pman_{$module}_UpdateDatabase";
475 if(!method_exists($x, 'checkOpts')){
478 $x->checkOpts($opts);
482 static function jsonImportFromArray($opts)
484 foreach($opts as $o=>$v) {
485 if (!preg_match('/^json-/', $o) || empty($v)) {
488 $type = str_replace('_', '-', substr($o,6));
489 $data= json_decode(file_get_contents($file),true);
490 DB_DataObject::factory($type)->importFromArray($this,$data,$opts);
498 function runUpdateModulesData()
502 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
503 echo "Running jsonImportFromArray\n";
504 Pman_Core_UpdateDatabase::jsonImportFromArray($this->opts);
507 echo "Running updateData on modules\n";
511 $modules = array_reverse($this->modulesList());
513 // move 'project' one to the end...
515 foreach ($modules as $module){
516 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
517 if($module == 'Core' || !file_exists($file)){
522 $class = "Pman_{$module}_UpdateDatabase";
524 if(!method_exists($x, 'updateData')){
534 function updateDataEnums()
536 $enum = DB_DataObject::Factory('core_enum');
541 'name' => 'COMPTYPE',
542 'display_name' => 'Company Types',
543 'is_system_enum' => 1,
547 'display_name' => 'Owner',
548 'seqid' => 999, // last...
549 'is_system_enum' => 1,
556 'name' => 'HtmlEditor.font-family',
557 'display_name' => 'HTML Editor font families',
558 'is_system_enum' => 1,
561 'name' => 'Helvetica,Arial,sans-serif',
562 'display_name' => 'Helvetica',
567 'name' => 'Courier New',
568 'display_name' => 'Courier',
573 'display_name' => 'Tahoma',
577 'name' => 'Times New Roman,serif',
578 'display_name' => 'Times',
583 'display_name' => 'Verdana',
595 function updateDataGroups()
598 $groups = DB_DataObject::factory('groups');
599 $groups->initGroups();
601 $groups->initDatabase($this,array(
603 'name' => 'bcc-email', // group who are bcc'ed on all requests.
604 'type' => 0, // system
611 function updateDataCompanies()
614 // fix comptypes enums..
615 $c = DB_DataObject::Factory('Companies');
617 $c->selectAdd('distinct(comptype) as comptype');
618 $c->whereAdd("comptype != ''");
621 foreach($c->fetchAll('comptype') as $cts) {
625 $ctb[]= array( 'etype'=>'COMPTYPE', 'name' => $cts, 'display_name' => ucfirst(strtolower($cts)));
628 $c = DB_DataObject::Factory('core_enum');
631 //DB_DataObject::debugLevel(1);
633 $c = DB_DataObject::Factory('Companies');
637 comptype_id = (SELECT id FROM core_enum where etype='comptype' and name=Companies.comptype)
650 function updateData()
654 $this->updateDataEnums();
655 $this->updateDataGroups();
656 $this->updateDataCompanies();
658 $c = DB_DataObject::Factory('I18n');
665 function fixSequencesPgsql()
667 //DB_DataObject::debugLevel(1);
668 $cs = DB_DataObject::factory('core_enum');
670 SELECT 'ALTER SEQUENCE '|| quote_ident(min(schema_name)) ||'.'|| quote_ident(min(seq_name))
671 ||' OWNED BY '|| quote_ident(min(schema_name)) || '.' ||
672 quote_ident(min(table_name)) ||'.'|| quote_ident(min(column_name)) ||';' as cmd
676 n.nspname AS schema_name,
677 c.relname AS table_name,
678 a.attname AS column_name,
679 regexp_replace(regexp_replace(d.adsrc, E'nextval\\\\(+[''\"]*', ''),E'[''\"]*::.*\$','') AS seq_name
681 JOIN pg_attribute a ON (c.oid=a.attrelid)
682 JOIN pg_attrdef d ON (a.attrelid=d.adrelid AND a.attnum=d.adnum)
683 JOIN pg_namespace n ON (c.relnamespace=n.oid)
684 WHERE has_schema_privilege(n.oid,'USAGE')
685 AND n.nspname NOT LIKE 'pg!_%' escape '!'
686 AND has_table_privilege(c.oid,'SELECT')
687 AND (NOT a.attisdropped)
688 AND d.adsrc ~ '^nextval'
691 GROUP BY seq_name HAVING count(*)=1
694 while ($cs->fetch()) {
697 foreach($cmds as $cmd) {
698 $cs = DB_DataObject::factory('core_enum');
701 $cs = DB_DataObject::factory('core_enum');
703 SELECT 'SELECT SETVAL(' ||
704 quote_literal(quote_ident(nspname) || '.' || quote_ident(S.relname)) ||
705 ', MAX(' || quote_ident(C.attname)|| ') ) FROM ' || nspname || '.' || quote_ident(T.relname)|| ';' as cmd
711 WHERE S.relkind = 'S'
713 AND D.refobjid = T.oid
714 AND D.refobjid = C.attrelid
715 AND D.refobjsubid = C.attnum
716 AND NS.oid = T.relnamespace
720 while ($cs->fetch()) {
723 foreach($cmds as $cmd) {
724 $cs = DB_DataObject::factory('core_enum');