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(
23 'desc' => 'prefix for the password (eg. fred > xxx4fred - prefix is xxx4)',
30 'desc' => 'only run the updateData - do not run import the tables and procedures.',
37 'add-company' => array(
38 'desc' => 'add a company name of the company',
44 'add-company-with-type' => array(
45 'desc' => 'the type of company (default OWNER)',
52 'desc' => 'Initialize the database (pg only supported)',
58 'only-module-sql' => array(
59 'desc' => 'Only run sql import on this modules - eg. Core',
64 'procedures-only' => array(
65 'desc' => 'Only import procedures (not supported by most modules yet) - ignores sql directory',
72 'json-person' => array(
73 'desc' => 'Person JSON file',
81 static function cli_opts()
84 $ret = self::$cli_opts;
85 $ff = HTML_FlexyFramework::get();
87 $mods = $a->modulesList();
88 foreach($mods as $m) {
90 $fd = $ff->rootDir. "/Pman/$m/UpdateDatabase.php";
91 if (!file_exists($fd)) {
97 $cls = new ReflectionClass('Pman_'. $m . '_UpdateDatabase');
99 $ret = array_merge($ret, $cls->getStaticPropertyValue('cli_opts'));
114 $ff = HTML_FlexyFramework::get();
115 if (!empty($ff->cli)) {
120 parent::getAuth(); // load company!
121 $au = $this->getAuthUser();
122 if (!$au || $au->company()->comptype != 'OWNER') {
123 $this->jerr("Not authenticated", array('authFailure' => true));
125 $this->authUser = $au;
129 function get($args, $opts)
131 PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, array($this, 'onPearError'));
133 $ff = HTML_FlexyFramework::get();
135 print_R(explode(',', $ff->disable));exit;
137 //$this->fixSequencesPgsql();exit;
140 // ask all the modules to verify the opts
142 $this->checkOpts($opts);
144 if (empty($opts['data-only'])) {
147 if (!empty($opts['only-module-sql'])) {
151 $this->runUpdateModulesData();
154 if (!empty($opts['add-company'])) {
155 // make sure we have a good cache...?
157 DB_DataObject::factory('companies')->initCompanies($this, $opts);
160 $this->runExtensions();
168 * imports SQL files from all DataObjects directories....
170 * except any matching /migrate/
175 // loop through all the modules, and see if they have a importSQL method?
178 $ff = HTML_Flexyframework::get();
180 $dburl = parse_url($ff->DB_DataObject['database']);
182 //$this->{'import' . $url['scheme']}($url);
184 $dbtype = $dburl['scheme'];
185 $dirmethod = 'import' . $dburl['scheme'] . 'dir';
190 $ar = $this->modulesList();
194 echo "Importing SQL from module $m\n";
195 if (!empty($this->opts['only-module-sql']) && $m != $this->opts['only-module-sql']) {
200 // check to see if the class has
204 $file = $this->rootDir. "/Pman/$m/UpdateDatabase.php";
205 if($m != 'Core' && file_exists($file)){
208 $class = "Pman_{$m}_UpdateDatabase";
210 if(method_exists($x, 'importModuleSQL')){
211 echo "Importing SQL from module $m using Module::importModuleSQL\n";
212 $x->opts = $this->opts;
213 $x->rootDir = $this->rootDir;
214 $x->importModuleSQL($dburl);
219 echo "Importing SQL from module $m\n";
222 // if init has been called
224 if (!empty($this->opts['init'])) {
225 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}.init");
231 $fd = $this->rootDir. "/Pman/$m/DataObjects";
233 $this->{$dirmethod}($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->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/sql");
240 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}");
244 if (!empty($this->opts['init']) && file_exists($this->rootDir. "/Pman/$m/{$dbtype}.initdata")) {
245 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
247 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}.initdata");
248 $this->{'fixSequences'. $dbtype}();
260 /** -------------- code to handle importing a whole directory of files into the database ------- **/
263 function importpgsqldir($url, $dir, $disable_triggers = false)
265 $ff = HTML_FlexyFramework::get();
267 require_once 'System.php';
268 $cat = System::which('cat');
269 $psql = System::which('psql');
272 if (!empty($url['pass'])) {
273 putenv("PGPASSWORD=". $url['pass']);
277 ' -h ' . $url['host'] .
278 ' -U' . escapeshellarg($url['user']) .
279 ' ' . basename($url['path']);
282 echo $psql_cmd . "\n" ;
283 echo "scan : $dir\n";
286 $files = array($dir);
291 $files = glob($dir.'/*.sql');
292 uksort($files, 'strcasecmp');
294 //$lsort = create_function('$a,$b','return strlen($a) > strlen($b) ? 1 : -1;');
295 //usort($files, $lsort);
298 foreach($files as $bfn) {
301 if (preg_match('/migrate/i', basename($bfn))) { // skip migration scripts at present..
304 if (preg_match('#\.[a-z]{2}\.sql#i', basename($bfn))
305 && !preg_match('#\.pg\.sql#i', basename($bfn))
306 ) { // skip migration scripts at present..
311 if (!preg_match('/pgsql/', basename($dir) )) {
312 if ( !preg_match('#\.pg\.sql$#', basename($bfn))) {
313 $fn = $this->convertToPG($bfn);
317 // files ending in .pg.sql are native postgres files.. ## depricated
320 $cmd = "$psql_cmd < " . escapeshellarg($fn ? $fn : $bfn) . ' 2>&1' ;
322 echo "$bfn: $cmd ". ($ff->cli ? "\n" : "<BR>\n");
338 * mysql - does not support conversions.
344 function importmysqldir($dburl, $dir)
347 $this->fixMysqlInnodb(); /// run once
349 echo "Import MYSQL :: $dir\n";
352 require_once 'System.php';
353 $cat = System::which('cat');
354 $mysql = System::which('mysql');
358 $mysql_cmd = $mysql .
359 ' -h ' . $dburl['host'] .
360 ' -u' . escapeshellarg($dburl['user']) .
361 (!empty($dburl['pass']) ? ' -p' . escapeshellarg($dburl['pass']) : '') .
362 ' ' . basename($dburl['path']);
363 //echo $mysql_cmd . "\n" ;
365 $files = glob($dir.'/*.sql');
366 uksort($files, 'strcasecmp');
369 foreach($files as $fn) {
372 if (preg_match('/migrate/i', basename($fn))) { // skip migration scripts at present..
375 // .my.sql but not .pg.sql
376 if (preg_match('#\.[a-z]{2}\.sql#i', basename($fn))
377 && !preg_match('#\.my\.sql#i', basename($fn))
378 ) { // skip migration scripts at present..
381 if (!strlen(trim($fn))) {
385 $cmd = "$mysql_cmd -f < " . escapeshellarg($fn) ;
387 echo basename($dir).'/'. basename($fn) . '::' . $cmd. ($this->cli ? "\n" : "<BR>\n");
400 * simple regex based convert mysql to pgsql...
402 function convertToPG($src)
404 //echo "Convert $src\n";
406 $fn = $this->tempName('sql');
408 $ret = array( ); // pad it a bit.
409 $extra = array("", "" );
412 foreach(file($src) as $l) {
415 if (!strlen($l) || $l[0] == '#') {
419 if (preg_match('#create\s+table\s+([a-z0-9_]+)#i', $l, $m)) {
422 if (preg_match('#create\s+table\s+\`([a-z0-9_]+)\`#i', $l, $m)) {
423 $tbl = 'shop_' . strtolower($m[1]);
424 $l = preg_replace('#create\s+table\s+\`([a-z0-9_]+)\`#i', "CREATE TABLE {$tbl}", $l);
426 if (preg_match('#\`([a-z0-9_]+)\`#i', $l, $m) && !preg_match('#alter\s+table\s+#i', $l)) {
427 $l = preg_replace('#\`([a-z0-9_]+)\`#i', "{$m[1]}_name", $l);
430 if ($tbl && preg_match('#auto_increment#i', $l, $m)) {
431 $l = preg_replace('#auto_increment#i', "default nextval('{$tbl}_seq')", $l);
432 $extra[] = "create sequence {$tbl}_seq;";
436 if (preg_match('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', $l, $m)){
437 $l = preg_replace('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', "ALTER TABLE {$tbl}", $l);
440 // enum value -- use the text instead..
442 if ($tbl && preg_match('#([\w]+)\s+(enum\([\w|\W]+\))#i', $l, $m)) {
443 $l = preg_replace('#enum\([\w|\W]+\)#i', "TEXT", $l);
445 // ignore the alter enum
446 if ($tbl && preg_match('#alter\s+table\s+([\w|\W]+)\s+enum\([\w|\W]+\)#i', $l, $m)) {
450 // UNIQUE KEY .. ignore
451 if ($tbl && preg_match('#UNIQUE KEY#i', $l, $m)) {
452 $last = array_pop($ret);
453 $ret[] = trim($last, ",");
457 if ($tbl && preg_match('#RENAME\s+TO#i', $l, $m)) {
461 if ($tbl && preg_match('#change\s+column#i', $l, $m)) {
465 // INDEX lookup ..ignore
466 if ($tbl && preg_match('#INDEX lookup+([\w|\W]+)#i', $l, $m)) {
467 $last = array_pop($ret);
468 $ret[] = trim($last, ",");
473 // CREATE INDEX ..ignore
474 if (preg_match('#alter\s+table\s+([a-z0-9_]+)\s+add\s+index\s+#i', $l, $m)) {
475 // $l = "CREATE INDEX {$m[1]}_{$m[2]} ON {$m[1]} {$m[3]}";
480 $l = preg_replace('#int\([0-9]+\)#i', 'INT', $l);
482 $l = preg_replace('# datetime#i', ' TIMESTAMP WITHOUT TIME ZONE', $l);
483 $l = preg_replace('# blob#i', ' TEXT', $l);
484 $l = preg_replace('# longtext#i', ' TEXT', $l);
485 $l = preg_replace('# tinyint#i', ' INT', $l);
491 $ret = array_merge($extra,$ret);
492 // echo implode("\n", $ret); exit;
494 file_put_contents($fn, implode("\n", $ret));
500 function checkOpts($opts)
504 foreach($opts as $o=>$v) {
505 if (!preg_match('/^json-/', $o) || empty($v)) {
508 if (!file_exists($v)) {
509 die("File does not exist : OPTION --{$o} = {$v} \n");
513 $modules = array_reverse($this->modulesList());
515 // move 'project' one to the end...
517 foreach ($modules as $module){
518 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
519 if($module == 'Core' || !file_exists($file)){
523 $class = "Pman_{$module}_UpdateDatabase";
525 if(!method_exists($x, 'checkOpts')){
528 $x->checkOpts($opts);
532 static function jsonImportFromArray($opts)
534 foreach($opts as $o=>$v) {
535 if (!preg_match('/^json-/', $o) || empty($v)) {
538 $type = str_replace('_', '-', substr($o,5));
540 $data= json_decode(file_get_contents($v),true);
541 $pg = HTML_FlexyFramework::get()->page;
542 DB_DataObject::factory($type)->importFromArray($pg ,$data,$opts);
552 function runUpdateModulesData()
556 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
557 echo "Running jsonImportFromArray\n";
558 Pman_Core_UpdateDatabase::jsonImportFromArray($this->opts);
561 echo "Running updateData on modules\n";
565 $modules = array_reverse($this->modulesList());
567 // move 'project' one to the end...
569 foreach ($modules as $module){
570 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
571 if($module == 'Core' || !file_exists($file)){
576 $class = "Pman_{$module}_UpdateDatabase";
578 if(!method_exists($x, 'updateData')){
588 function updateDataEnums()
591 $enum = DB_DataObject::Factory('core_enum');
592 //DB_DAtaObject::debugLevel(1);
597 'name' => 'COMPTYPE',
598 'display_name' => 'Company Types',
599 'is_system_enum' => 1,
603 'display_name' => 'Owner',
604 'seqid' => 999, // last...
605 'is_system_enum' => 1,
612 'name' => 'HtmlEditor.font-family',
613 'display_name' => 'HTML Editor font families',
614 'is_system_enum' => 1,
617 'name' => 'Helvetica,Arial,sans-serif',
618 'display_name' => 'Helvetica',
623 'name' => 'Courier New',
624 'display_name' => 'Courier',
629 'display_name' => 'Tahoma',
633 'name' => 'Times New Roman,serif',
634 'display_name' => 'Times',
639 'display_name' => 'Verdana',
651 function updateDataGroups()
654 $groups = DB_DataObject::factory('groups');
655 $groups->initGroups();
657 $groups->initDatabase($this,array(
659 'name' => 'bcc-email', // group who are bcc'ed on all requests.
660 'type' => 0, // system
663 'name' => 'system-email-from',
664 'type' => 0, // system
667 'name' => 'core-person-signup-bcc',
668 'type' => 0, // system
674 function updateDataCompanies()
677 // fix comptypes enums..
678 $c = DB_DataObject::Factory('Companies');
680 $c->selectAdd('distinct(comptype) as comptype');
681 $c->whereAdd("comptype != ''");
684 foreach($c->fetchAll('comptype') as $cts) {
688 $ctb[]= array( 'etype'=>'COMPTYPE', 'name' => $cts, 'display_name' => ucfirst(strtolower($cts)));
691 $c = DB_DataObject::Factory('core_enum');
694 //DB_DataObject::debugLevel(1);
696 $c = DB_DataObject::Factory('Companies');
700 comptype_id = (SELECT id FROM core_enum where etype='comptype' and name=Companies.comptype LIMIT 1)
713 function updateData()
716 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
717 $this->updateDataEnums();
718 $this->updateDataGroups();
719 $this->updateDataCompanies();
721 $c = DB_DataObject::Factory('I18n');
729 function fixMysqlInnodb()
732 static $done_check = false;
736 // innodb in single files is far more efficient that MYD or one big innodb file.
737 // first check if database is using this format.
738 $db = DB_DataObject::factory('core_enum');
739 $db->query("show variables like 'innodb_file_per_table'");
741 if ($db->Value == 'OFF') {
742 die("Error: set innodb_file_per_table = 1 in my.cnf\n\n");
756 /** ------------- schema fixing ... there is an issue with data imported having the wrong sequence names... --- */
758 function fixSequencesMysql()
763 function fixSequencesPgsql()
767 //DB_DataObject::debugLevel(1);
768 $cs = DB_DataObject::factory('core_enum');
772 CASE WHEN strpos(seq_name, '.') > 0 THEN
775 quote_ident(min(schema_name)) ||'.'|| quote_ident(min(seq_name))
778 ||' OWNED BY '|| quote_ident(min(schema_name)) || '.' ||
779 quote_ident(min(table_name)) ||'.'|| quote_ident(min(column_name)) ||';' as cmd
783 n.nspname AS schema_name,
784 c.relname AS table_name,
785 a.attname AS column_name,
786 regexp_replace(regexp_replace(d.adsrc, E'nextval\\\\(+[''\\\"]*', ''),E'[''\\\"]*::.*\$','') AS seq_name
788 JOIN pg_attribute a ON (c.oid=a.attrelid)
789 JOIN pg_attrdef d ON (a.attrelid=d.adrelid AND a.attnum=d.adnum)
790 JOIN pg_namespace n ON (c.relnamespace=n.oid)
791 WHERE has_schema_privilege(n.oid,'USAGE')
792 AND n.nspname NOT LIKE 'pg!_%' escape '!'
793 AND has_table_privilege(c.oid,'SELECT')
794 AND (NOT a.attisdropped)
795 AND d.adsrc ~ '^nextval'
799 CASE WHEN strpos(seq_name, '.') > 0 THEN
800 substring(seq_name, 1,strpos(seq_name,'.')-1)
805 GROUP BY seq_name HAVING count(*)=1
808 while ($cs->fetch()) {
811 foreach($cmds as $cmd) {
812 $cs = DB_DataObject::factory('core_enum');
816 $cs = DB_DataObject::factory('core_enum');
818 SELECT 'SELECT SETVAL(' ||
819 quote_literal(quote_ident(nspname) || '.' || quote_ident(S.relname)) ||
820 ', MAX(' || quote_ident(C.attname)|| ')::integer ) FROM ' || nspname || '.' || quote_ident(T.relname)|| ';' as cmd
826 WHERE S.relkind = 'S'
828 AND D.refobjid = T.oid
829 AND D.refobjid = C.attrelid
830 AND D.refobjsubid = C.attnum
831 AND NS.oid = T.relnamespace
835 while ($cs->fetch()) {
838 foreach($cmds as $cmd) {
839 $cs = DB_DataObject::factory('core_enum');
846 var $extensions = array(
851 function runExtensions()
854 $ff = HTML_Flexyframework::get();
856 $dburl = parse_url($ff->DB_DataObject['database']);
858 $dbtype = $dburl['scheme'];
860 foreach($this->extensions as $ext) {
862 $scls = ucfirst($dbtype). $ext;
863 $cls = __CLASS__ . '_'. $scls;
864 $fn = implode('/',explode('_', $cls)).'.php';
865 if (!file_exists(__DIR__.'/UpdateDatabase/'. $scls .'.php')) {