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'));
86 var $cli_options = false;
93 $ff = HTML_FlexyFramework::get();
94 if (!empty($ff->cli)) {
99 parent::getAuth(); // load company!
100 $au = $this->getAuthUser();
101 if (!$au || $au->company()->comptype != 'OWNER') {
102 $this->jerr("Not authenticated", array('authFailure' => true));
104 $this->authUser = $au;
108 function get($args, $opt)
111 $this->cli_options = $opt;
113 if($args == 'Person'){
114 if(empty($opt['source']) || empty($opt['prefix'])){
115 die("Missing Source directory for person json files or prefix for the passwrod! Try -f [JSON file path] -p [prefix] \n");
117 if (!file_exists($opt['source'])) {
118 die("can not found person json file : {$opt['source']} \n");
121 $persons = json_decode(file_get_contents($opt['source']),true);
123 DB_DataObject::factory('person')->importFromArray($this, $persons, $opt['prefix']);
129 if($args == 'Company'){
130 if(empty($opt['name']) || empty($opt['comptype'])){
131 die("Missing company name or type! Try --name=[the name of company] -- comptype=[the type of company] \n");
134 DB_DataObject::factory('companies')->initCompanies($this, $opt['name'], $opt['comptype']);
140 $this->runUpdateModulesData();
147 * imports SQL files from all DataObjects directories....
149 * except any matching /migrate/
154 $ff = HTML_Flexyframework::get();
156 $url = parse_url($ff->DB_DataObject['database']);
158 $this->{'import' . $url['scheme']}($url);
163 * mysql - does not support conversions.
169 function importmysqldir($dburl, $dir)
171 echo "Import MYSQL :: $dir\n";
174 require_once 'System.php';
175 $cat = System::which('cat');
176 $mysql = System::which('mysql');
180 $mysql_cmd = $mysql .
181 ' -h ' . $dburl['host'] .
182 ' -u' . escapeshellarg($dburl['user']) .
183 (!empty($dburl['pass']) ? ' -p' . escapeshellarg($dburl['pass']) : '') .
184 ' ' . basename($dburl['path']);
185 //echo $mysql_cmd . "\n" ;
188 foreach(glob($dir.'/*.sql') as $fn) {
191 if (preg_match('/migrate/i', basename($fn))) { // skip migration scripts at present..
194 // .my.sql but not .pg.sql
195 if (preg_match('#\.[a-z]{2}\.sql#i', basename($fn))
196 && !preg_match('#\.my\.sql#i', basename($fn))
197 ) { // skip migration scripts at present..
200 if (!strlen(trim($fn))) {
204 $cmd = "$mysql_cmd -f < " . escapeshellarg($fn) ;
206 echo basename($dir).'/'. basename($fn) . '::' . $cmd. ($this->cli ? "\n" : "<BR>\n");
219 function importmysql($dburl)
222 // hide stuff for web..
223 $ar = $this->modulesList();
227 // old -- DAtaObjects/*.sql
231 $fd = $this->rootDir. "/Pman/$m/DataObjects";
233 $this->importmysqldir($dburl, $fd);
235 // new -- sql directory..
236 // new style will not support migrate ... they have to go into mysql-migrate.... directories..
237 // new style will not support pg.sql etc.. naming - that's what the direcotries are for..
239 $this->importmysqldir($dburl, $this->rootDir. "/Pman/$m/sql");
240 $this->importmysqldir($dburl, $this->rootDir. "/Pman/$m/mysql");
249 * postgresql import..
251 function importpgsql($dburl)
254 // hide stuff for web..
259 $ar = $this->modulesList();
263 // if init has been called
265 if (!empty($this->cli_options['init'])) {
266 $this->importpgsqldir($dburl, $this->rootDir. "/Pman/$m/pgsql.init");
272 $fd = $this->rootDir. "/Pman/$m/DataObjects";
274 $this->importpgsqldir($dburl, $fd);
276 // new -- sql directory..
277 // new style will not support migrate ... they have to go into mysql-migrate.... directories..
278 // new style will not support pg.sql etc.. naming - that's what the direcotries are for..
280 $this->importpgsqldir($dburl, $this->rootDir. "/Pman/$m/sql");
281 $this->importpgsqldir($dburl, $this->rootDir. "/Pman/$m/pgsql");
285 if (!empty($this->cli_options['init']) && file_exists($this->rootDir. "/Pman/$m/pgsql.initdata")) {
286 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
288 $this->importpgsqldir($dburl, $this->rootDir. "/Pman/$m/pgsql.initdata");
289 $this->fixSequencesPgsql();
298 function importpgsqldir($url, $dir, $disable_triggers = false)
300 require_once 'System.php';
301 $cat = System::which('cat');
302 $psql = System::which('psql');
305 if (!empty($url['pass'])) {
306 putenv("PGPASSWORD=". $url['pass']);
310 ' -h ' . $url['host'] .
311 ' -U' . escapeshellarg($url['user']) .
312 ' ' . basename($url['path']);
315 echo $psql_cmd . "\n" ;
316 echo "scan : $dir\n";
317 foreach(glob($dir.'/*.sql') as $bfn) {
320 if (preg_match('/migrate/i', basename($bfn))) { // skip migration scripts at present..
323 if (preg_match('#\.[a-z]{2}\.sql#i', basename($bfn))
324 && !preg_match('#\.pg\.sql#i', basename($bfn))
325 ) { // skip migration scripts at present..
330 if (!preg_match('/pgsql/', basename($dir) )) {
331 if ( !preg_match('#\.pg\.sql$#', basename($bfn))) {
332 $fn = $this->convertToPG($bfn);
336 // files ending in .pg.sql are native postgres files.. ## depricated
339 $cmd = "$psql_cmd < " . escapeshellarg($fn ? $fn : $bfn) . ' 2>&1' ;
341 echo "$bfn: $cmd ". ($this->cli ? "\n" : "<BR>\n");
356 * simple regex based convert mysql to pgsql...
358 function convertToPG($src)
360 //echo "Convert $src\n";
362 $fn = $this->tempName('sql');
364 $ret = array( ); // pad it a bit.
365 $extra = array("", "" );
368 foreach(file($src) as $l) {
371 if (!strlen($l) || $l[0] == '#') {
375 if (preg_match('#create\s+table\s+([a-z0-9_]+)#i', $l, $m)) {
378 if (preg_match('#create\s+table\s+\`([a-z0-9_]+)\`#i', $l, $m)) {
379 $tbl = 'shop_' . strtolower($m[1]);
380 $l = preg_replace('#create\s+table\s+\`([a-z0-9_]+)\`#i', "CREATE TABLE {$tbl}", $l);
382 if (preg_match('#\`([a-z0-9_]+)\`#i', $l, $m) && !preg_match('#alter\s+table\s+#i', $l)) {
383 $l = preg_replace('#\`([a-z0-9_]+)\`#i', "{$m[1]}_name", $l);
386 if ($tbl && preg_match('#auto_increment#i', $l, $m)) {
387 $l = preg_replace('#auto_increment#i', "default nextval('{$tbl}_seq')", $l);
388 $extra[] = "create sequence {$tbl}_seq;";
392 if (preg_match('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', $l, $m)){
393 $l = preg_replace('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', "ALTER TABLE {$tbl}", $l);
396 // enum value -- use the text instead..
398 if ($tbl && preg_match('#([\w]+)\s+(enum\([\w|\W]+\))#i', $l, $m)) {
399 $l = preg_replace('#enum\([\w|\W]+\)#i', "TEXT", $l);
401 // ignore the alter enum
402 if ($tbl && preg_match('#alter\s+table\s+([\w|\W]+)\s+enum\([\w|\W]+\)#i', $l, $m)) {
406 // UNIQUE KEY .. ignore
407 if ($tbl && preg_match('#UNIQUE KEY#i', $l, $m)) {
408 $last = array_pop($ret);
409 $ret[] = trim($last, ",");
413 if ($tbl && preg_match('#RENAME\s+TO#i', $l, $m)) {
417 if ($tbl && preg_match('#change\s+column#i', $l, $m)) {
421 // INDEX lookup ..ignore
422 if ($tbl && preg_match('#INDEX lookup+([\w|\W]+)#i', $l, $m)) {
423 $last = array_pop($ret);
424 $ret[] = trim($last, ",");
429 // CREATE INDEX ..ignore
430 if (preg_match('#alter\s+table\s+([a-z0-9_]+)\s+add\s+index\s+#i', $l, $m)) {
431 // $l = "CREATE INDEX {$m[1]}_{$m[2]} ON {$m[1]} {$m[3]}";
436 $l = preg_replace('#int\([0-9]+\)#i', 'INT', $l);
438 $l = preg_replace('# datetime#i', ' TIMESTAMP WITHOUT TIME ZONE', $l);
439 $l = preg_replace('# blob#i', ' TEXT', $l);
440 $l = preg_replace('# longtext#i', ' TEXT', $l);
441 $l = preg_replace('# tinyint#i', ' INT', $l);
447 $ret = array_merge($extra,$ret);
448 // echo implode("\n", $ret); exit;
450 file_put_contents($fn, implode("\n", $ret));
455 function runUpdateModulesData()
457 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
462 $modules = array_reverse($this->modulesList());
464 // move 'project' one to the end...
466 foreach ($modules as $module){
467 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
468 if($module == 'Core' || !file_exists($file)){
472 $class = "Pman_{$module}_UpdateDatabase";
474 if(!method_exists($x, 'updateData')){
483 function updateDataEnums()
485 $enum = DB_DataObject::Factory('core_enum');
490 'name' => 'COMPTYPE',
491 'display_name' => 'Company Types',
492 'is_system_enum' => 1,
496 'display_name' => 'Owner',
497 'seqid' => 999, // last...
498 'is_system_enum' => 1,
505 'name' => 'HtmlEditor.font-family',
506 'display_name' => 'HTML Editor font families',
507 'is_system_enum' => 1,
510 'name' => 'Helvetica,Arial,sans-serif',
511 'display_name' => 'Helvetica',
516 'name' => 'Courier New',
517 'display_name' => 'Courier',
522 'display_name' => 'Tahoma',
526 'name' => 'Times New Roman,serif',
527 'display_name' => 'Times',
532 'display_name' => 'Verdana',
544 function updateDataGroups()
547 $groups = DB_DataObject::factory('groups');
548 $groups->initGroups();
550 $groups->initDatabase($this,array(
552 'name' => 'bcc-email', // group who are bcc'ed on all requests.
553 'type' => 0, // system
560 function updateDataCompanies()
563 // fix comptypes enums..
564 $c = DB_DataObject::Factory('Companies');
566 $c->selectAdd('distinct(comptype) as comptype');
567 $c->whereAdd("comptype != ''");
570 foreach($c->fetchAll('comptype') as $cts) {
574 $ctb[]= array( 'etype'=>'COMPTYPE', 'name' => $cts, 'display_name' => ucfirst(strtolower($cts)));
577 $c = DB_DataObject::Factory('core_enum');
580 //DB_DataObject::debugLevel(1);
582 $c = DB_DataObject::Factory('Companies');
586 comptype_id = (SELECT id FROM core_enum where etype='comptype' and name=Companies.comptype)
599 function updateData()
603 $this->updateDataEnums();
604 $this->updateDataGroups();
605 $this->updateDataCompanies();
607 $c = DB_DataObject::Factory('I18n');
614 function fixSequencesPgsql()
616 DB_DataObject::debugLevel(1);
617 $cs = DB_DataObject::factory('core_enum');
619 SELECT 'SELECT SETVAL(' ||
620 quote_literal(quote_ident(nspname) || '.' || quote_ident(S.relname)) ||
621 ', MAX(' || quote_ident(C.attname)|| ') ) FROM ' || nspname || '.' || quote_ident(T.relname)|| ';' as cmd
627 WHERE S.relkind = 'S'
629 AND D.refobjid = T.oid
630 AND D.refobjid = C.attrelid
631 AND D.refobjsubid = C.attnum
632 AND NS.oid = T.relnamespace
635 while ($cs->fetch()) {
638 foreach($cmds as $cmd) {
639 $cs = DB_DataObject::factory('core_enum');