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()
61 die("query cli_opts");
62 return self::$cli_opts;
65 var $cli_options = false;
72 $ff = HTML_FlexyFramework::get();
73 if (!empty($ff->cli)) {
78 parent::getAuth(); // load company!
79 $au = $this->getAuthUser();
80 if (!$au || $au->company()->comptype != 'OWNER') {
81 $this->jerr("Not authenticated", array('authFailure' => true));
83 $this->authUser = $au;
87 function get($args, $opt)
90 $this->cli_options = $opt;
92 if($args == 'Person'){
93 if(empty($opt['source']) || empty($opt['prefix'])){
94 die("Missing Source directory for person json files or prefix for the passwrod! Try -f [JSON file path] -p [prefix] \n");
96 if (!file_exists($opt['source'])) {
97 die("can not found person json file : {$opt['source']} \n");
100 $persons = json_decode(file_get_contents($opt['source']),true);
102 DB_DataObject::factory('person')->importFromArray($this, $persons, $opt['prefix']);
108 if($args == 'Company'){
109 if(empty($opt['name']) || empty($opt['comptype'])){
110 die("Missing company name or type! Try --name=[the name of company] -- comptype=[the type of company] \n");
113 DB_DataObject::factory('companies')->initCompanies($this, $opt['name'], $opt['comptype']);
119 $this->runUpdateModulesData();
126 * imports SQL files from all DataObjects directories....
128 * except any matching /migrate/
133 $ff = HTML_Flexyframework::get();
135 $url = parse_url($ff->DB_DataObject['database']);
137 $this->{'import' . $url['scheme']}($url);
142 * mysql - does not support conversions.
148 function importmysqldir($dburl, $dir)
150 echo "Import MYSQL :: $dir\n";
153 require_once 'System.php';
154 $cat = System::which('cat');
155 $mysql = System::which('mysql');
159 $mysql_cmd = $mysql .
160 ' -h ' . $dburl['host'] .
161 ' -u' . escapeshellarg($dburl['user']) .
162 (!empty($dburl['pass']) ? ' -p' . escapeshellarg($dburl['pass']) : '') .
163 ' ' . basename($dburl['path']);
164 //echo $mysql_cmd . "\n" ;
167 foreach(glob($dir.'/*.sql') as $fn) {
170 if (preg_match('/migrate/i', basename($fn))) { // skip migration scripts at present..
173 // .my.sql but not .pg.sql
174 if (preg_match('#\.[a-z]{2}\.sql#i', basename($fn))
175 && !preg_match('#\.my\.sql#i', basename($fn))
176 ) { // skip migration scripts at present..
179 if (!strlen(trim($fn))) {
183 $cmd = "$mysql_cmd -f < " . escapeshellarg($fn) ;
185 echo basename($dir).'/'. basename($fn) . '::' . $cmd. ($this->cli ? "\n" : "<BR>\n");
198 function importmysql($dburl)
201 // hide stuff for web..
202 $ar = $this->modulesList();
206 // old -- DAtaObjects/*.sql
210 $fd = $this->rootDir. "/Pman/$m/DataObjects";
212 $this->importmysqldir($dburl, $fd);
214 // new -- sql directory..
215 // new style will not support migrate ... they have to go into mysql-migrate.... directories..
216 // new style will not support pg.sql etc.. naming - that's what the direcotries are for..
218 $this->importmysqldir($dburl, $this->rootDir. "/Pman/$m/sql");
219 $this->importmysqldir($dburl, $this->rootDir. "/Pman/$m/mysql");
228 * postgresql import..
230 function importpgsql($dburl)
233 // hide stuff for web..
238 $ar = $this->modulesList();
242 // if init has been called
244 if (!empty($this->cli_options['init'])) {
245 $this->importpgsqldir($dburl, $this->rootDir. "/Pman/$m/pgsql.init");
251 $fd = $this->rootDir. "/Pman/$m/DataObjects";
253 $this->importpgsqldir($dburl, $fd);
255 // new -- sql directory..
256 // new style will not support migrate ... they have to go into mysql-migrate.... directories..
257 // new style will not support pg.sql etc.. naming - that's what the direcotries are for..
259 $this->importpgsqldir($dburl, $this->rootDir. "/Pman/$m/sql");
260 $this->importpgsqldir($dburl, $this->rootDir. "/Pman/$m/pgsql");
264 if (!empty($this->cli_options['init']) && file_exists($this->rootDir. "/Pman/$m/pgsql.initdata")) {
265 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
267 $this->importpgsqldir($dburl, $this->rootDir. "/Pman/$m/pgsql.initdata");
268 $this->fixSequencesPgsql();
277 function importpgsqldir($url, $dir, $disable_triggers = false)
279 require_once 'System.php';
280 $cat = System::which('cat');
281 $psql = System::which('psql');
284 if (!empty($url['pass'])) {
285 putenv("PGPASSWORD=". $url['pass']);
289 ' -h ' . $url['host'] .
290 ' -U' . escapeshellarg($url['user']) .
291 ' ' . basename($url['path']);
294 echo $psql_cmd . "\n" ;
295 echo "scan : $dir\n";
296 foreach(glob($dir.'/*.sql') as $bfn) {
299 if (preg_match('/migrate/i', basename($bfn))) { // skip migration scripts at present..
302 if (preg_match('#\.[a-z]{2}\.sql#i', basename($bfn))
303 && !preg_match('#\.pg\.sql#i', basename($bfn))
304 ) { // skip migration scripts at present..
309 if (!preg_match('/pgsql/', basename($dir) )) {
310 if ( !preg_match('#\.pg\.sql$#', basename($bfn))) {
311 $fn = $this->convertToPG($bfn);
315 // files ending in .pg.sql are native postgres files.. ## depricated
318 $cmd = "$psql_cmd < " . escapeshellarg($fn ? $fn : $bfn) . ' 2>&1' ;
320 echo "$bfn: $cmd ". ($this->cli ? "\n" : "<BR>\n");
335 * simple regex based convert mysql to pgsql...
337 function convertToPG($src)
339 //echo "Convert $src\n";
341 $fn = $this->tempName('sql');
343 $ret = array( ); // pad it a bit.
344 $extra = array("", "" );
347 foreach(file($src) as $l) {
350 if (!strlen($l) || $l[0] == '#') {
354 if (preg_match('#create\s+table\s+([a-z0-9_]+)#i', $l, $m)) {
357 if (preg_match('#create\s+table\s+\`([a-z0-9_]+)\`#i', $l, $m)) {
358 $tbl = 'shop_' . strtolower($m[1]);
359 $l = preg_replace('#create\s+table\s+\`([a-z0-9_]+)\`#i', "CREATE TABLE {$tbl}", $l);
361 if (preg_match('#\`([a-z0-9_]+)\`#i', $l, $m) && !preg_match('#alter\s+table\s+#i', $l)) {
362 $l = preg_replace('#\`([a-z0-9_]+)\`#i', "{$m[1]}_name", $l);
365 if ($tbl && preg_match('#auto_increment#i', $l, $m)) {
366 $l = preg_replace('#auto_increment#i', "default nextval('{$tbl}_seq')", $l);
367 $extra[] = "create sequence {$tbl}_seq;";
371 if (preg_match('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', $l, $m)){
372 $l = preg_replace('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', "ALTER TABLE {$tbl}", $l);
375 // enum value -- use the text instead..
377 if ($tbl && preg_match('#([\w]+)\s+(enum\([\w|\W]+\))#i', $l, $m)) {
378 $l = preg_replace('#enum\([\w|\W]+\)#i', "TEXT", $l);
380 // ignore the alter enum
381 if ($tbl && preg_match('#alter\s+table\s+([\w|\W]+)\s+enum\([\w|\W]+\)#i', $l, $m)) {
385 // UNIQUE KEY .. ignore
386 if ($tbl && preg_match('#UNIQUE KEY#i', $l, $m)) {
387 $last = array_pop($ret);
388 $ret[] = trim($last, ",");
392 if ($tbl && preg_match('#RENAME\s+TO#i', $l, $m)) {
396 if ($tbl && preg_match('#change\s+column#i', $l, $m)) {
400 // INDEX lookup ..ignore
401 if ($tbl && preg_match('#INDEX lookup+([\w|\W]+)#i', $l, $m)) {
402 $last = array_pop($ret);
403 $ret[] = trim($last, ",");
408 // CREATE INDEX ..ignore
409 if (preg_match('#alter\s+table\s+([a-z0-9_]+)\s+add\s+index\s+#i', $l, $m)) {
410 // $l = "CREATE INDEX {$m[1]}_{$m[2]} ON {$m[1]} {$m[3]}";
415 $l = preg_replace('#int\([0-9]+\)#i', 'INT', $l);
417 $l = preg_replace('# datetime#i', ' TIMESTAMP WITHOUT TIME ZONE', $l);
418 $l = preg_replace('# blob#i', ' TEXT', $l);
419 $l = preg_replace('# longtext#i', ' TEXT', $l);
420 $l = preg_replace('# tinyint#i', ' INT', $l);
426 $ret = array_merge($extra,$ret);
427 // echo implode("\n", $ret); exit;
429 file_put_contents($fn, implode("\n", $ret));
434 function runUpdateModulesData()
436 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
441 $modules = array_reverse($this->modulesList());
443 // move 'project' one to the end...
445 foreach ($modules as $module){
446 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
447 if($module == 'Core' || !file_exists($file)){
451 $class = "Pman_{$module}_UpdateDatabase";
453 if(!method_exists($x, 'updateData')){
462 function updateDataEnums()
464 $enum = DB_DataObject::Factory('core_enum');
469 'name' => 'COMPTYPE',
470 'display_name' => 'Company Types',
471 'is_system_enum' => 1,
475 'display_name' => 'Owner',
476 'seqid' => 999, // last...
477 'is_system_enum' => 1,
484 'name' => 'HtmlEditor.font-family',
485 'display_name' => 'HTML Editor font families',
486 'is_system_enum' => 1,
489 'name' => 'Helvetica,Arial,sans-serif',
490 'display_name' => 'Helvetica',
495 'name' => 'Courier New',
496 'display_name' => 'Courier',
501 'display_name' => 'Tahoma',
505 'name' => 'Times New Roman,serif',
506 'display_name' => 'Times',
511 'display_name' => 'Verdana',
523 function updateDataGroups()
526 $groups = DB_DataObject::factory('groups');
527 $groups->initGroups();
529 $groups->initDatabase($this,array(
531 'name' => 'bcc-email', // group who are bcc'ed on all requests.
532 'type' => 0, // system
539 function updateDataCompanies()
542 // fix comptypes enums..
543 $c = DB_DataObject::Factory('Companies');
545 $c->selectAdd('distinct(comptype) as comptype');
546 $c->whereAdd("comptype != ''");
549 foreach($c->fetchAll('comptype') as $cts) {
553 $ctb[]= array( 'etype'=>'COMPTYPE', 'name' => $cts, 'display_name' => ucfirst(strtolower($cts)));
556 $c = DB_DataObject::Factory('core_enum');
559 //DB_DataObject::debugLevel(1);
561 $c = DB_DataObject::Factory('Companies');
565 comptype_id = (SELECT id FROM core_enum where etype='comptype' and name=Companies.comptype)
578 function updateData()
582 $this->updateDataEnums();
583 $this->updateDataGroups();
584 $this->updateDataCompanies();
586 $c = DB_DataObject::Factory('I18n');
593 function fixSequencesPgsql()
595 DB_DataObject::debugLevel(1);
596 $cs = DB_DataObject::factory('core_enum');
598 SELECT 'SELECT SETVAL(' ||
599 quote_literal(quote_ident(nspname) || '.' || quote_ident(S.relname)) ||
600 ', MAX(' || quote_ident(C.attname)|| ') ) FROM ' || nspname || '.' || quote_ident(T.relname)|| ';' as cmd
606 WHERE S.relkind = 'S'
608 AND D.refobjid = T.oid
609 AND D.refobjid = C.attrelid
610 AND D.refobjsubid = C.attnum
611 AND NS.oid = T.relnamespace
614 while ($cs->fetch()) {
617 foreach($cmds as $cmd) {
618 $cs = DB_DataObject::factory('core_enum');