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)',
60 var $cli_options = false;
66 $ff = HTML_FlexyFramework::get();
67 if (!empty($ff->cli)) {
72 parent::getAuth(); // load company!
73 $au = $this->getAuthUser();
74 if (!$au || $au->company()->comptype != 'OWNER') {
75 $this->jerr("Not authenticated", array('authFailure' => true));
77 $this->authUser = $au;
81 function get($args, $opt)
84 $this->cli_options = $opt;
86 if($args == 'Person'){
87 if(empty($opt['source']) || empty($opt['prefix'])){
88 die("Missing Source directory for person json files or prefix for the passwrod! Try -f [JSON file path] -p [prefix] \n");
90 if (!file_exists($opt['source'])) {
91 die("can not found person json file : {$opt['source']} \n");
94 $persons = json_decode(file_get_contents($opt['source']),true);
96 DB_DataObject::factory('person')->importFromArray($this, $persons, $opt['prefix']);
102 if($args == 'Company'){
103 if(empty($opt['name']) || empty($opt['comptype'])){
104 die("Missing company name or type! Try --name=[the name of company] -- comptype=[the type of company] \n");
107 DB_DataObject::factory('companies')->initCompanies($this, $opt['name'], $opt['comptype']);
113 $this->runUpdateModulesData();
120 * imports SQL files from all DataObjects directories....
122 * except any matching /migrate/
127 $ff = HTML_Flexyframework::get();
129 $url = parse_url($ff->DB_DataObject['database']);
131 $this->{'import' . $url['scheme']}($url);
136 * mysql - does not support conversions.
142 function importmysqldir($dburl, $dir)
144 echo "Import MYSQL :: $dir\n";
147 require_once 'System.php';
148 $cat = System::which('cat');
149 $mysql = System::which('mysql');
153 $mysql_cmd = $mysql .
154 ' -h ' . $dburl['host'] .
155 ' -u' . escapeshellarg($dburl['user']) .
156 (!empty($dburl['pass']) ? ' -p' . escapeshellarg($dburl['pass']) : '') .
157 ' ' . basename($dburl['path']);
158 //echo $mysql_cmd . "\n" ;
161 foreach(glob($dir.'/*.sql') as $fn) {
164 if (preg_match('/migrate/i', basename($fn))) { // skip migration scripts at present..
167 // .my.sql but not .pg.sql
168 if (preg_match('#\.[a-z]{2}\.sql#i', basename($fn))
169 && !preg_match('#\.my\.sql#i', basename($fn))
170 ) { // skip migration scripts at present..
173 if (!strlen(trim($fn))) {
177 $cmd = "$mysql_cmd -f < " . escapeshellarg($fn) ;
179 echo basename($dir).'/'. basename($fn) . '::' . $cmd. ($this->cli ? "\n" : "<BR>\n");
192 function importmysql($dburl)
195 // hide stuff for web..
196 $ar = $this->modulesList();
200 // old -- DAtaObjects/*.sql
204 $fd = $this->rootDir. "/Pman/$m/DataObjects";
206 $this->importmysqldir($dburl, $fd);
208 // new -- sql directory..
209 // new style will not support migrate ... they have to go into mysql-migrate.... directories..
210 // new style will not support pg.sql etc.. naming - that's what the direcotries are for..
212 $this->importmysqldir($dburl, $this->rootDir. "/Pman/$m/sql");
213 $this->importmysqldir($dburl, $this->rootDir. "/Pman/$m/mysql");
222 * postgresql import..
224 function importpgsql($dburl)
227 // hide stuff for web..
232 $ar = $this->modulesList();
236 // if init has been called
238 if (!empty($this->cli_options['init'])) {
239 $this->importpgsqldir($dburl, $this->rootDir. "/Pman/$m/pgsql.init");
245 $fd = $this->rootDir. "/Pman/$m/DataObjects";
247 $this->importpgsqldir($dburl, $fd);
249 // new -- sql directory..
250 // new style will not support migrate ... they have to go into mysql-migrate.... directories..
251 // new style will not support pg.sql etc.. naming - that's what the direcotries are for..
253 $this->importpgsqldir($dburl, $this->rootDir. "/Pman/$m/sql");
254 $this->importpgsqldir($dburl, $this->rootDir. "/Pman/$m/pgsql");
258 if (!empty($this->cli_options['init']) && file_exists($this->rootDir. "/Pman/$m/pgsql.initdata")) {
259 HTML_FlexyFramework::get()->generateDataobjectsCache();
261 $this->importpgsqldir($dburl, $this->rootDir. "/Pman/$m/pgsql.initdata");
262 $this->fixSequencesPgsql();
271 function importpgsqldir($url, $dir, $disable_triggers = false)
273 require_once 'System.php';
274 $cat = System::which('cat');
275 $psql = System::which('psql');
278 if (!empty($url['pass'])) {
279 putenv("PGPASSWORD=". $url['pass']);
283 ' -h ' . $url['host'] .
284 ' -U' . escapeshellarg($url['user']) .
285 ' ' . basename($url['path']);
288 echo $psql_cmd . "\n" ;
289 echo "scan : $dir\n";
290 foreach(glob($dir.'/*.sql') as $bfn) {
293 if (preg_match('/migrate/i', basename($bfn))) { // skip migration scripts at present..
296 if (preg_match('#\.[a-z]{2}\.sql#i', basename($bfn))
297 && !preg_match('#\.pg\.sql#i', basename($bfn))
298 ) { // skip migration scripts at present..
303 if (!preg_match('/pgsql/', basename($dir) )) {
304 if ( !preg_match('#\.pg\.sql$#', basename($bfn))) {
305 $fn = $this->convertToPG($bfn);
309 // files ending in .pg.sql are native postgres files.. ## depricated
312 $cmd = "$psql_cmd < " . escapeshellarg($fn ? $fn : $bfn) . ' 2>&1' ;
314 echo "$bfn: $cmd ". ($this->cli ? "\n" : "<BR>\n");
329 * simple regex based convert mysql to pgsql...
331 function convertToPG($src)
333 //echo "Convert $src\n";
335 $fn = $this->tempName('sql');
337 $ret = array( ); // pad it a bit.
338 $extra = array("", "" );
341 foreach(file($src) as $l) {
344 if (!strlen($l) || $l[0] == '#') {
348 if (preg_match('#create\s+table\s+([a-z0-9_]+)#i', $l, $m)) {
351 if (preg_match('#create\s+table\s+\`([a-z0-9_]+)\`#i', $l, $m)) {
352 $tbl = 'shop_' . strtolower($m[1]);
353 $l = preg_replace('#create\s+table\s+\`([a-z0-9_]+)\`#i', "CREATE TABLE {$tbl}", $l);
355 if (preg_match('#\`([a-z0-9_]+)\`#i', $l, $m) && !preg_match('#alter\s+table\s+#i', $l)) {
356 $l = preg_replace('#\`([a-z0-9_]+)\`#i', "{$m[1]}_name", $l);
359 if ($tbl && preg_match('#auto_increment#i', $l, $m)) {
360 $l = preg_replace('#auto_increment#i', "default nextval('{$tbl}_seq')", $l);
361 $extra[] = "create sequence {$tbl}_seq;";
365 if (preg_match('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', $l, $m)){
366 $l = preg_replace('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', "ALTER TABLE {$tbl}", $l);
369 // enum value -- use the text instead..
371 if ($tbl && preg_match('#([\w]+)\s+(enum\([\w|\W]+\))#i', $l, $m)) {
372 $l = preg_replace('#enum\([\w|\W]+\)#i', "TEXT", $l);
374 // ignore the alter enum
375 if ($tbl && preg_match('#alter\s+table\s+([\w|\W]+)\s+enum\([\w|\W]+\)#i', $l, $m)) {
379 // UNIQUE KEY .. ignore
380 if ($tbl && preg_match('#UNIQUE KEY#i', $l, $m)) {
381 $last = array_pop($ret);
382 $ret[] = trim($last, ",");
386 if ($tbl && preg_match('#RENAME\s+TO#i', $l, $m)) {
390 if ($tbl && preg_match('#change\s+column#i', $l, $m)) {
394 // INDEX lookup ..ignore
395 if ($tbl && preg_match('#INDEX lookup+([\w|\W]+)#i', $l, $m)) {
396 $last = array_pop($ret);
397 $ret[] = trim($last, ",");
402 // CREATE INDEX ..ignore
403 if (preg_match('#alter\s+table\s+([a-z0-9_]+)\s+add\s+index\s+#i', $l, $m)) {
404 // $l = "CREATE INDEX {$m[1]}_{$m[2]} ON {$m[1]} {$m[3]}";
409 $l = preg_replace('#int\([0-9]+\)#i', 'INT', $l);
411 $l = preg_replace('# datetime#i', ' TIMESTAMP WITHOUT TIME ZONE', $l);
412 $l = preg_replace('# blob#i', ' TEXT', $l);
413 $l = preg_replace('# longtext#i', ' TEXT', $l);
414 $l = preg_replace('# tinyint#i', ' INT', $l);
420 $ret = array_merge($extra,$ret);
421 // echo implode("\n", $ret); exit;
423 file_put_contents($fn, implode("\n", $ret));
428 function runUpdateModulesData()
432 $modules = array_reverse($this->modulesList());
434 // move 'project' one to the end...
436 foreach ($modules as $module){
437 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
438 if($module == 'Core' || !file_exists($file)){
442 $class = "Pman_{$module}_UpdateDatabase";
444 if(!method_exists($x, 'updateData')){
453 function updateDataEnums()
455 $enum = DB_DataObject::Factory('core_enum');
460 'name' => 'COMPTYPE',
461 'display_name' => 'Company Types',
462 'is_system_enum' => 1,
466 'display_name' => 'Owner',
467 'seqid' => 999, // last...
468 'is_system_enum' => 1,
475 'name' => 'HtmlEditor.font-family',
476 'display_name' => 'HTML Editor font families',
477 'is_system_enum' => 1,
480 'name' => 'Helvetica,Arial,sans-serif',
481 'display_name' => 'Helvetica',
486 'name' => 'Courier New',
487 'display_name' => 'Courier',
492 'display_name' => 'Tahoma',
496 'name' => 'Times New Roman,serif',
497 'display_name' => 'Times',
502 'display_name' => 'Verdana',
514 function updateDataGroups()
517 $groups = DB_DataObject::factory('groups');
518 $groups->initGroups();
520 $groups->initDatabase($this,array(
522 'name' => 'bcc-email', // group who are bcc'ed on all requests.
523 'type' => 0, // system
530 function updateDataCompanies()
533 // fix comptypes enums..
534 $c = DB_DataObject::Factory('Companies');
536 $c->selectAdd('distinct(comptype) as comptype');
537 $c->whereAdd("comptype != ''");
540 foreach($c->fetchAll('comptype') as $cts) {
544 $ctb[]= array( 'etype'=>'COMPTYPE', 'name' => $cts, 'display_name' => ucfirst(strtolower($cts)));
547 $c = DB_DataObject::Factory('core_enum');
550 //DB_DataObject::debugLevel(1);
552 $c = DB_DataObject::Factory('Companies');
556 comptype_id = (SELECT id FROM core_enum where etype='comptype' and name=Companies.comptype)
569 function updateData()
573 $this->updateDataEnums();
574 $this->updateDataGroups();
575 $this->updateDataCompanies();
577 $c = DB_DataObject::Factory('I18n');
584 function fixSequencesPgsql()
586 DB_DataObject::debugLevel(1);
587 $cs = DB_DataObject::factory('core_enum');
589 SELECT 'SELECT SETVAL(' ||
590 quote_literal(quote_ident(nspname) || '.' || quote_ident(S.relname)) ||
591 ', MAX(' || quote_ident(C.attname)|| ') ) FROM ' || nspname || '.' || quote_ident(T.relname)|| ';' as cmd
597 WHERE S.relkind = 'S'
599 AND D.refobjid = T.oid
600 AND D.refobjid = C.attrelid
601 AND D.refobjsubid = C.attnum
602 AND NS.oid = T.relnamespace
605 while ($cs->fetch()) {
608 foreach($cmds as $cmd) {
609 $cs = DB_DataObject::factory('core_enum');