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(
22 'desc' => 'Source directory for json files.',
29 'desc' => 'prefix for the passwrod',
36 'desc' => 'name of the company',
43 'desc' => 'the type of company',
50 'desc' => 'Initialize the database (pg only supported)',
59 static function cli_opts()
62 $ret = self::$cli_opts;
63 $ff = HTML_FlexyFramework::get();
65 $mods = $a->modulesList();
66 foreach($mods as $m) {
68 $fd = $ff->rootDir. "/Pman/$m/UpdateDatabase.php";
69 if (!file_exists($fd)) {
75 $cls = new ReflectionClass('Pman_'. $m . '_UpdateDatabase');
77 $ret = array_merge($ret, $cls->getStaticPropertyValue('cli_opts'));
85 var $cli_options = false;
92 $ff = HTML_FlexyFramework::get();
93 if (!empty($ff->cli)) {
98 parent::getAuth(); // load company!
99 $au = $this->getAuthUser();
100 if (!$au || $au->company()->comptype != 'OWNER') {
101 $this->jerr("Not authenticated", array('authFailure' => true));
103 $this->authUser = $au;
107 function get($args, $opt)
110 $this->cli_options = $opt;
112 if($args == 'Person'){
113 if(empty($opt['source']) || empty($opt['prefix'])){
114 die("Missing Source directory for person json files or prefix for the passwrod! Try -f [JSON file path] -p [prefix] \n");
116 if (!file_exists($opt['source'])) {
117 die("can not found person json file : {$opt['source']} \n");
120 $persons = json_decode(file_get_contents($opt['source']),true);
122 DB_DataObject::factory('person')->importFromArray($this, $persons, $opt['prefix']);
128 if($args == 'Company'){
129 if(empty($opt['name']) || empty($opt['comptype'])){
130 die("Missing company name or type! Try --name=[the name of company] -- comptype=[the type of company] \n");
133 DB_DataObject::factory('companies')->initCompanies($this, $opt['name'], $opt['comptype']);
139 $this->runUpdateModulesData();
146 * imports SQL files from all DataObjects directories....
148 * except any matching /migrate/
153 $ff = HTML_Flexyframework::get();
155 $url = parse_url($ff->DB_DataObject['database']);
157 $this->{'import' . $url['scheme']}($url);
162 * mysql - does not support conversions.
168 function importmysqldir($dburl, $dir)
170 echo "Import MYSQL :: $dir\n";
173 require_once 'System.php';
174 $cat = System::which('cat');
175 $mysql = System::which('mysql');
179 $mysql_cmd = $mysql .
180 ' -h ' . $dburl['host'] .
181 ' -u' . escapeshellarg($dburl['user']) .
182 (!empty($dburl['pass']) ? ' -p' . escapeshellarg($dburl['pass']) : '') .
183 ' ' . basename($dburl['path']);
184 //echo $mysql_cmd . "\n" ;
187 foreach(glob($dir.'/*.sql') as $fn) {
190 if (preg_match('/migrate/i', basename($fn))) { // skip migration scripts at present..
193 // .my.sql but not .pg.sql
194 if (preg_match('#\.[a-z]{2}\.sql#i', basename($fn))
195 && !preg_match('#\.my\.sql#i', basename($fn))
196 ) { // skip migration scripts at present..
199 if (!strlen(trim($fn))) {
203 $cmd = "$mysql_cmd -f < " . escapeshellarg($fn) ;
205 echo basename($dir).'/'. basename($fn) . '::' . $cmd. ($this->cli ? "\n" : "<BR>\n");
218 function importmysql($dburl)
221 // hide stuff for web..
222 $ar = $this->modulesList();
226 // old -- DAtaObjects/*.sql
230 $fd = $this->rootDir. "/Pman/$m/DataObjects";
232 $this->importmysqldir($dburl, $fd);
234 // new -- sql directory..
235 // new style will not support migrate ... they have to go into mysql-migrate.... directories..
236 // new style will not support pg.sql etc.. naming - that's what the direcotries are for..
238 $this->importmysqldir($dburl, $this->rootDir. "/Pman/$m/sql");
239 $this->importmysqldir($dburl, $this->rootDir. "/Pman/$m/mysql");
248 * postgresql import..
250 function importpgsql($dburl)
253 // hide stuff for web..
258 $ar = $this->modulesList();
262 // if init has been called
264 if (!empty($this->cli_options['init'])) {
265 $this->importpgsqldir($dburl, $this->rootDir. "/Pman/$m/pgsql.init");
271 $fd = $this->rootDir. "/Pman/$m/DataObjects";
273 $this->importpgsqldir($dburl, $fd);
275 // new -- sql directory..
276 // new style will not support migrate ... they have to go into mysql-migrate.... directories..
277 // new style will not support pg.sql etc.. naming - that's what the direcotries are for..
279 $this->importpgsqldir($dburl, $this->rootDir. "/Pman/$m/sql");
280 $this->importpgsqldir($dburl, $this->rootDir. "/Pman/$m/pgsql");
284 if (!empty($this->cli_options['init']) && file_exists($this->rootDir. "/Pman/$m/pgsql.initdata")) {
285 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
287 $this->importpgsqldir($dburl, $this->rootDir. "/Pman/$m/pgsql.initdata");
288 $this->fixSequencesPgsql();
297 function importpgsqldir($url, $dir, $disable_triggers = false)
299 require_once 'System.php';
300 $cat = System::which('cat');
301 $psql = System::which('psql');
304 if (!empty($url['pass'])) {
305 putenv("PGPASSWORD=". $url['pass']);
309 ' -h ' . $url['host'] .
310 ' -U' . escapeshellarg($url['user']) .
311 ' ' . basename($url['path']);
314 echo $psql_cmd . "\n" ;
315 echo "scan : $dir\n";
316 foreach(glob($dir.'/*.sql') as $bfn) {
319 if (preg_match('/migrate/i', basename($bfn))) { // skip migration scripts at present..
322 if (preg_match('#\.[a-z]{2}\.sql#i', basename($bfn))
323 && !preg_match('#\.pg\.sql#i', basename($bfn))
324 ) { // skip migration scripts at present..
329 if (!preg_match('/pgsql/', basename($dir) )) {
330 if ( !preg_match('#\.pg\.sql$#', basename($bfn))) {
331 $fn = $this->convertToPG($bfn);
335 // files ending in .pg.sql are native postgres files.. ## depricated
338 $cmd = "$psql_cmd < " . escapeshellarg($fn ? $fn : $bfn) . ' 2>&1' ;
340 echo "$bfn: $cmd ". ($this->cli ? "\n" : "<BR>\n");
355 * simple regex based convert mysql to pgsql...
357 function convertToPG($src)
359 //echo "Convert $src\n";
361 $fn = $this->tempName('sql');
363 $ret = array( ); // pad it a bit.
364 $extra = array("", "" );
367 foreach(file($src) as $l) {
370 if (!strlen($l) || $l[0] == '#') {
374 if (preg_match('#create\s+table\s+([a-z0-9_]+)#i', $l, $m)) {
377 if (preg_match('#create\s+table\s+\`([a-z0-9_]+)\`#i', $l, $m)) {
378 $tbl = 'shop_' . strtolower($m[1]);
379 $l = preg_replace('#create\s+table\s+\`([a-z0-9_]+)\`#i', "CREATE TABLE {$tbl}", $l);
381 if (preg_match('#\`([a-z0-9_]+)\`#i', $l, $m) && !preg_match('#alter\s+table\s+#i', $l)) {
382 $l = preg_replace('#\`([a-z0-9_]+)\`#i', "{$m[1]}_name", $l);
385 if ($tbl && preg_match('#auto_increment#i', $l, $m)) {
386 $l = preg_replace('#auto_increment#i', "default nextval('{$tbl}_seq')", $l);
387 $extra[] = "create sequence {$tbl}_seq;";
391 if (preg_match('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', $l, $m)){
392 $l = preg_replace('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', "ALTER TABLE {$tbl}", $l);
395 // enum value -- use the text instead..
397 if ($tbl && preg_match('#([\w]+)\s+(enum\([\w|\W]+\))#i', $l, $m)) {
398 $l = preg_replace('#enum\([\w|\W]+\)#i', "TEXT", $l);
400 // ignore the alter enum
401 if ($tbl && preg_match('#alter\s+table\s+([\w|\W]+)\s+enum\([\w|\W]+\)#i', $l, $m)) {
405 // UNIQUE KEY .. ignore
406 if ($tbl && preg_match('#UNIQUE KEY#i', $l, $m)) {
407 $last = array_pop($ret);
408 $ret[] = trim($last, ",");
412 if ($tbl && preg_match('#RENAME\s+TO#i', $l, $m)) {
416 if ($tbl && preg_match('#change\s+column#i', $l, $m)) {
420 // INDEX lookup ..ignore
421 if ($tbl && preg_match('#INDEX lookup+([\w|\W]+)#i', $l, $m)) {
422 $last = array_pop($ret);
423 $ret[] = trim($last, ",");
428 // CREATE INDEX ..ignore
429 if (preg_match('#alter\s+table\s+([a-z0-9_]+)\s+add\s+index\s+#i', $l, $m)) {
430 // $l = "CREATE INDEX {$m[1]}_{$m[2]} ON {$m[1]} {$m[3]}";
435 $l = preg_replace('#int\([0-9]+\)#i', 'INT', $l);
437 $l = preg_replace('# datetime#i', ' TIMESTAMP WITHOUT TIME ZONE', $l);
438 $l = preg_replace('# blob#i', ' TEXT', $l);
439 $l = preg_replace('# longtext#i', ' TEXT', $l);
440 $l = preg_replace('# tinyint#i', ' INT', $l);
446 $ret = array_merge($extra,$ret);
447 // echo implode("\n", $ret); exit;
449 file_put_contents($fn, implode("\n", $ret));
454 function runUpdateModulesData()
456 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
461 $modules = array_reverse($this->modulesList());
463 // move 'project' one to the end...
465 foreach ($modules as $module){
466 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
467 if($module == 'Core' || !file_exists($file)){
471 $class = "Pman_{$module}_UpdateDatabase";
473 if(!method_exists($x, 'updateData')){
482 function updateDataEnums()
484 $enum = DB_DataObject::Factory('core_enum');
489 'name' => 'COMPTYPE',
490 'display_name' => 'Company Types',
491 'is_system_enum' => 1,
495 'display_name' => 'Owner',
496 'seqid' => 999, // last...
497 'is_system_enum' => 1,
504 'name' => 'HtmlEditor.font-family',
505 'display_name' => 'HTML Editor font families',
506 'is_system_enum' => 1,
509 'name' => 'Helvetica,Arial,sans-serif',
510 'display_name' => 'Helvetica',
515 'name' => 'Courier New',
516 'display_name' => 'Courier',
521 'display_name' => 'Tahoma',
525 'name' => 'Times New Roman,serif',
526 'display_name' => 'Times',
531 'display_name' => 'Verdana',
543 function updateDataGroups()
546 $groups = DB_DataObject::factory('groups');
547 $groups->initGroups();
549 $groups->initDatabase($this,array(
551 'name' => 'bcc-email', // group who are bcc'ed on all requests.
552 'type' => 0, // system
559 function updateDataCompanies()
562 // fix comptypes enums..
563 $c = DB_DataObject::Factory('Companies');
565 $c->selectAdd('distinct(comptype) as comptype');
566 $c->whereAdd("comptype != ''");
569 foreach($c->fetchAll('comptype') as $cts) {
573 $ctb[]= array( 'etype'=>'COMPTYPE', 'name' => $cts, 'display_name' => ucfirst(strtolower($cts)));
576 $c = DB_DataObject::Factory('core_enum');
579 //DB_DataObject::debugLevel(1);
581 $c = DB_DataObject::Factory('Companies');
585 comptype_id = (SELECT id FROM core_enum where etype='comptype' and name=Companies.comptype)
598 function updateData()
602 $this->updateDataEnums();
603 $this->updateDataGroups();
604 $this->updateDataCompanies();
606 $c = DB_DataObject::Factory('I18n');
613 function fixSequencesPgsql()
615 DB_DataObject::debugLevel(1);
616 $cs = DB_DataObject::factory('core_enum');
618 SELECT 'SELECT SETVAL(' ||
619 quote_literal(quote_ident(nspname) || '.' || quote_ident(S.relname)) ||
620 ', MAX(' || quote_ident(C.attname)|| ') ) FROM ' || nspname || '.' || quote_ident(T.relname)|| ';' as cmd
626 WHERE S.relkind = 'S'
628 AND D.refobjid = T.oid
629 AND D.refobjid = C.attrelid
630 AND D.refobjsubid = C.attnum
631 AND NS.oid = T.relnamespace
634 while ($cs->fetch()) {
637 foreach($cmds as $cmd) {
638 $cs = DB_DataObject::factory('core_enum');