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)',
61 return self::$cli_opts;
64 var $cli_options = false;
71 $ff = HTML_FlexyFramework::get();
72 if (!empty($ff->cli)) {
77 parent::getAuth(); // load company!
78 $au = $this->getAuthUser();
79 if (!$au || $au->company()->comptype != 'OWNER') {
80 $this->jerr("Not authenticated", array('authFailure' => true));
82 $this->authUser = $au;
86 function get($args, $opt)
89 $this->cli_options = $opt;
91 if($args == 'Person'){
92 if(empty($opt['source']) || empty($opt['prefix'])){
93 die("Missing Source directory for person json files or prefix for the passwrod! Try -f [JSON file path] -p [prefix] \n");
95 if (!file_exists($opt['source'])) {
96 die("can not found person json file : {$opt['source']} \n");
99 $persons = json_decode(file_get_contents($opt['source']),true);
101 DB_DataObject::factory('person')->importFromArray($this, $persons, $opt['prefix']);
107 if($args == 'Company'){
108 if(empty($opt['name']) || empty($opt['comptype'])){
109 die("Missing company name or type! Try --name=[the name of company] -- comptype=[the type of company] \n");
112 DB_DataObject::factory('companies')->initCompanies($this, $opt['name'], $opt['comptype']);
118 $this->runUpdateModulesData();
125 * imports SQL files from all DataObjects directories....
127 * except any matching /migrate/
132 $ff = HTML_Flexyframework::get();
134 $url = parse_url($ff->DB_DataObject['database']);
136 $this->{'import' . $url['scheme']}($url);
141 * mysql - does not support conversions.
147 function importmysqldir($dburl, $dir)
149 echo "Import MYSQL :: $dir\n";
152 require_once 'System.php';
153 $cat = System::which('cat');
154 $mysql = System::which('mysql');
158 $mysql_cmd = $mysql .
159 ' -h ' . $dburl['host'] .
160 ' -u' . escapeshellarg($dburl['user']) .
161 (!empty($dburl['pass']) ? ' -p' . escapeshellarg($dburl['pass']) : '') .
162 ' ' . basename($dburl['path']);
163 //echo $mysql_cmd . "\n" ;
166 foreach(glob($dir.'/*.sql') as $fn) {
169 if (preg_match('/migrate/i', basename($fn))) { // skip migration scripts at present..
172 // .my.sql but not .pg.sql
173 if (preg_match('#\.[a-z]{2}\.sql#i', basename($fn))
174 && !preg_match('#\.my\.sql#i', basename($fn))
175 ) { // skip migration scripts at present..
178 if (!strlen(trim($fn))) {
182 $cmd = "$mysql_cmd -f < " . escapeshellarg($fn) ;
184 echo basename($dir).'/'. basename($fn) . '::' . $cmd. ($this->cli ? "\n" : "<BR>\n");
197 function importmysql($dburl)
200 // hide stuff for web..
201 $ar = $this->modulesList();
205 // old -- DAtaObjects/*.sql
209 $fd = $this->rootDir. "/Pman/$m/DataObjects";
211 $this->importmysqldir($dburl, $fd);
213 // new -- sql directory..
214 // new style will not support migrate ... they have to go into mysql-migrate.... directories..
215 // new style will not support pg.sql etc.. naming - that's what the direcotries are for..
217 $this->importmysqldir($dburl, $this->rootDir. "/Pman/$m/sql");
218 $this->importmysqldir($dburl, $this->rootDir. "/Pman/$m/mysql");
227 * postgresql import..
229 function importpgsql($dburl)
232 // hide stuff for web..
237 $ar = $this->modulesList();
241 // if init has been called
243 if (!empty($this->cli_options['init'])) {
244 $this->importpgsqldir($dburl, $this->rootDir. "/Pman/$m/pgsql.init");
250 $fd = $this->rootDir. "/Pman/$m/DataObjects";
252 $this->importpgsqldir($dburl, $fd);
254 // new -- sql directory..
255 // new style will not support migrate ... they have to go into mysql-migrate.... directories..
256 // new style will not support pg.sql etc.. naming - that's what the direcotries are for..
258 $this->importpgsqldir($dburl, $this->rootDir. "/Pman/$m/sql");
259 $this->importpgsqldir($dburl, $this->rootDir. "/Pman/$m/pgsql");
263 if (!empty($this->cli_options['init']) && file_exists($this->rootDir. "/Pman/$m/pgsql.initdata")) {
264 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
266 $this->importpgsqldir($dburl, $this->rootDir. "/Pman/$m/pgsql.initdata");
267 $this->fixSequencesPgsql();
276 function importpgsqldir($url, $dir, $disable_triggers = false)
278 require_once 'System.php';
279 $cat = System::which('cat');
280 $psql = System::which('psql');
283 if (!empty($url['pass'])) {
284 putenv("PGPASSWORD=". $url['pass']);
288 ' -h ' . $url['host'] .
289 ' -U' . escapeshellarg($url['user']) .
290 ' ' . basename($url['path']);
293 echo $psql_cmd . "\n" ;
294 echo "scan : $dir\n";
295 foreach(glob($dir.'/*.sql') as $bfn) {
298 if (preg_match('/migrate/i', basename($bfn))) { // skip migration scripts at present..
301 if (preg_match('#\.[a-z]{2}\.sql#i', basename($bfn))
302 && !preg_match('#\.pg\.sql#i', basename($bfn))
303 ) { // skip migration scripts at present..
308 if (!preg_match('/pgsql/', basename($dir) )) {
309 if ( !preg_match('#\.pg\.sql$#', basename($bfn))) {
310 $fn = $this->convertToPG($bfn);
314 // files ending in .pg.sql are native postgres files.. ## depricated
317 $cmd = "$psql_cmd < " . escapeshellarg($fn ? $fn : $bfn) . ' 2>&1' ;
319 echo "$bfn: $cmd ". ($this->cli ? "\n" : "<BR>\n");
334 * simple regex based convert mysql to pgsql...
336 function convertToPG($src)
338 //echo "Convert $src\n";
340 $fn = $this->tempName('sql');
342 $ret = array( ); // pad it a bit.
343 $extra = array("", "" );
346 foreach(file($src) as $l) {
349 if (!strlen($l) || $l[0] == '#') {
353 if (preg_match('#create\s+table\s+([a-z0-9_]+)#i', $l, $m)) {
356 if (preg_match('#create\s+table\s+\`([a-z0-9_]+)\`#i', $l, $m)) {
357 $tbl = 'shop_' . strtolower($m[1]);
358 $l = preg_replace('#create\s+table\s+\`([a-z0-9_]+)\`#i', "CREATE TABLE {$tbl}", $l);
360 if (preg_match('#\`([a-z0-9_]+)\`#i', $l, $m) && !preg_match('#alter\s+table\s+#i', $l)) {
361 $l = preg_replace('#\`([a-z0-9_]+)\`#i', "{$m[1]}_name", $l);
364 if ($tbl && preg_match('#auto_increment#i', $l, $m)) {
365 $l = preg_replace('#auto_increment#i', "default nextval('{$tbl}_seq')", $l);
366 $extra[] = "create sequence {$tbl}_seq;";
370 if (preg_match('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', $l, $m)){
371 $l = preg_replace('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', "ALTER TABLE {$tbl}", $l);
374 // enum value -- use the text instead..
376 if ($tbl && preg_match('#([\w]+)\s+(enum\([\w|\W]+\))#i', $l, $m)) {
377 $l = preg_replace('#enum\([\w|\W]+\)#i', "TEXT", $l);
379 // ignore the alter enum
380 if ($tbl && preg_match('#alter\s+table\s+([\w|\W]+)\s+enum\([\w|\W]+\)#i', $l, $m)) {
384 // UNIQUE KEY .. ignore
385 if ($tbl && preg_match('#UNIQUE KEY#i', $l, $m)) {
386 $last = array_pop($ret);
387 $ret[] = trim($last, ",");
391 if ($tbl && preg_match('#RENAME\s+TO#i', $l, $m)) {
395 if ($tbl && preg_match('#change\s+column#i', $l, $m)) {
399 // INDEX lookup ..ignore
400 if ($tbl && preg_match('#INDEX lookup+([\w|\W]+)#i', $l, $m)) {
401 $last = array_pop($ret);
402 $ret[] = trim($last, ",");
407 // CREATE INDEX ..ignore
408 if (preg_match('#alter\s+table\s+([a-z0-9_]+)\s+add\s+index\s+#i', $l, $m)) {
409 // $l = "CREATE INDEX {$m[1]}_{$m[2]} ON {$m[1]} {$m[3]}";
414 $l = preg_replace('#int\([0-9]+\)#i', 'INT', $l);
416 $l = preg_replace('# datetime#i', ' TIMESTAMP WITHOUT TIME ZONE', $l);
417 $l = preg_replace('# blob#i', ' TEXT', $l);
418 $l = preg_replace('# longtext#i', ' TEXT', $l);
419 $l = preg_replace('# tinyint#i', ' INT', $l);
425 $ret = array_merge($extra,$ret);
426 // echo implode("\n", $ret); exit;
428 file_put_contents($fn, implode("\n", $ret));
433 function runUpdateModulesData()
435 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
440 $modules = array_reverse($this->modulesList());
442 // move 'project' one to the end...
444 foreach ($modules as $module){
445 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
446 if($module == 'Core' || !file_exists($file)){
450 $class = "Pman_{$module}_UpdateDatabase";
452 if(!method_exists($x, 'updateData')){
461 function updateDataEnums()
463 $enum = DB_DataObject::Factory('core_enum');
468 'name' => 'COMPTYPE',
469 'display_name' => 'Company Types',
470 'is_system_enum' => 1,
474 'display_name' => 'Owner',
475 'seqid' => 999, // last...
476 'is_system_enum' => 1,
483 'name' => 'HtmlEditor.font-family',
484 'display_name' => 'HTML Editor font families',
485 'is_system_enum' => 1,
488 'name' => 'Helvetica,Arial,sans-serif',
489 'display_name' => 'Helvetica',
494 'name' => 'Courier New',
495 'display_name' => 'Courier',
500 'display_name' => 'Tahoma',
504 'name' => 'Times New Roman,serif',
505 'display_name' => 'Times',
510 'display_name' => 'Verdana',
522 function updateDataGroups()
525 $groups = DB_DataObject::factory('groups');
526 $groups->initGroups();
528 $groups->initDatabase($this,array(
530 'name' => 'bcc-email', // group who are bcc'ed on all requests.
531 'type' => 0, // system
538 function updateDataCompanies()
541 // fix comptypes enums..
542 $c = DB_DataObject::Factory('Companies');
544 $c->selectAdd('distinct(comptype) as comptype');
545 $c->whereAdd("comptype != ''");
548 foreach($c->fetchAll('comptype') as $cts) {
552 $ctb[]= array( 'etype'=>'COMPTYPE', 'name' => $cts, 'display_name' => ucfirst(strtolower($cts)));
555 $c = DB_DataObject::Factory('core_enum');
558 //DB_DataObject::debugLevel(1);
560 $c = DB_DataObject::Factory('Companies');
564 comptype_id = (SELECT id FROM core_enum where etype='comptype' and name=Companies.comptype)
577 function updateData()
581 $this->updateDataEnums();
582 $this->updateDataGroups();
583 $this->updateDataCompanies();
585 $c = DB_DataObject::Factory('I18n');
592 function fixSequencesPgsql()
594 DB_DataObject::debugLevel(1);
595 $cs = DB_DataObject::factory('core_enum');
597 SELECT 'SELECT SETVAL(' ||
598 quote_literal(quote_ident(nspname) || '.' || quote_ident(S.relname)) ||
599 ', MAX(' || quote_ident(C.attname)|| ') ) FROM ' || nspname || '.' || quote_ident(T.relname)|| ';' as cmd
605 WHERE S.relkind = 'S'
607 AND D.refobjid = T.oid
608 AND D.refobjid = C.attrelid
609 AND D.refobjsubid = C.attnum
610 AND NS.oid = T.relnamespace
613 while ($cs->fetch()) {
616 foreach($cmds as $cmd) {
617 $cs = DB_DataObject::factory('core_enum');