674ca5785747a3d1e79025f470f3c089e7c5fce8
[Pman.Builder] / DataObjects / Builder_tables.php
1 <?php
2 /**
3  * Table Definition for builder_tables
4  */
5 require_once 'DB/DataObject.php';
6
7 class Pman_Builder_DataObjects_Builder_tables extends DB_DataObject 
8 {
9     ###START_AUTOCODE
10     /* the code below is auto generated do not remove the above tag */
11
12     public $__table = 'builder_tables';      // table name
13     public $id;                              // int(11)  not_null primary_key auto_increment
14     public $name;                            // string(128)  not_null
15     public $descrip;                         // string(254)  not_null
16     public $parent_id;                       // int(11)  not_null multiple_key
17     public $dbschema;                        // blob(65535)  not_null blob
18
19     
20     /* the code above is auto generated do not remove the tag below */
21     ###END_AUTOCODE
22     
23     
24     function applyFilters($q, $au)
25     {
26         //DB_DataObject::debugLEvel(1);
27         if (!empty($q['_sync'])) {
28             $this->syncDatabase();
29             HTML_FlexyFramework::get()->page->jok("DONE");
30         }
31         
32         if(!empty($q['_dumpDatabase'])){
33             $this->dumpDatabase();
34         }
35         
36 //        if(!empty($q['_dumpTable'])){
37 //            $this->dumpTable($q['_dumpTable']);
38 //        }
39        
40     }
41     
42     function syncDatabase()
43     {
44         //DB_DataObject::debugLevel(1);
45         global $_DB_DATAOBJECT;
46         $x = DB_DataObject::factory('builder_tables');
47         $x->whereAdd("name != ''"); // real tables only..
48         $mine = $this->fetchAll('name', 'id');
49         
50         // ensure everything is loaded...
51         $tq = DB_DataObject::factory('builder_tables');
52         $tq->table();
53         $tq->links();
54         $tables = $_DB_DATAOBJECT['INI'][$tq->_database];
55         
56          
57         $ret = array();
58         $t = array_keys($tables);
59         sort($t);
60         
61         
62         // for postgres we can get descriptions - this should just fail in Mysql..
63         $desc= array();
64         $dsn = HTML_FlexyFramework::get()->database;
65         
66         if (preg_match('/^pgsql:/', $dsn )) {
67             $tq = DB_DataObject::factory('builder_tables');
68             $tq->query( "
69                 select relname, obj_description( oid) as desc FROM pg_catalog.pg_class
70                 ");
71             while ($tq->fetch()) {
72                 $desc[$tq->relname] = $tq->desc;
73             }
74         }
75         //   DB_DataObjecT::DebugLevel(1);
76         $tq = DB_DataObject::factory('builder_tables');
77         
78         require_once 'Services/JSON.php';
79         
80         $modids = array();
81         
82         
83         foreach( $t as $k) {
84             if (preg_match('/__keys$/', $k)) {
85                 continue;
86             }
87             // check it can be constructed..
88             // this might be problematic for 'new' tables...
89             $do = DB_DataObject::factory($k);
90             if (!is_a($do,'DB_DataObject')) {
91                 continue;
92             }
93             
94             // get's the module part out of the dataobject class name
95             // assumes '_' is not used in module name.
96             $mod = array_pop(
97                     explode('_',
98                         substr(get_class($do), 0, -1 * (strlen('_DataObject_') + strlen($k)+ 1))
99                     ));
100              
101             // should get 'ZZZ' part.. : XXX_ZZZZ_DataObject_xx_Builder
102             if (!isset($modids[$mod])) {
103                 $x = DB_DataObject::factory('builder_tables');
104                 $x->parent_id =0;
105                 $x->name = '';
106                 $x->descrip = $mod;
107                 $x->dbschema = '';
108                 if (!$x->find(true)) {
109                     $x->insert();
110                 } 
111                  $modids[$mod] = $x->id; 
112                 
113             }
114             
115             
116             
117             $set = array(
118                 'name' => $k,
119                 'descrip' => isset($desc[$k]) ? $desc[$k] : '',
120                 'dbschema' => Services_JSON::stringify($this->tableSchema($k),null,4),
121                // 'parent_id' =>  $modids[$mod],
122             );
123             
124             $do = clone($tq);
125             if (isset($mine[$k])) { 
126                 $do->get($mine[$k]);
127                 $dd = clone($do);
128                 $do->setFrom($set);
129                 if (empty($do->parent_id) || $do->parent_id < 1) {
130                     // allow user to modify this..
131                     $do->parent_id = $modids[$mod];
132                 }
133                 $do->update($dd);
134                 continue;
135             }
136             
137             $do->setFrom($set);
138             $do->parent_id = $modids[$mod];
139             $do->insert();
140         
141         }
142             
143         
144         
145     }
146     
147     
148     function tableSchema($tn)
149     {
150         static  $cache = array();
151         static  $types= array();
152         $do = DB_DataObject::factory($tn);
153         $tn = $do->tableName(); // cleaned up!
154
155
156         if (isset($cache[$tn])) {
157             return $cache[$tn];
158         }
159
160         // get a description if available..
161        
162              
163         $desc = array();
164         $dd = clone($do);
165         $dsn = HTML_FlexyFramework::get()->database;
166         if (preg_match('/^pgsql:/', $dsn)) {
167             
168             
169            // DB_DataObject::DebugLevel(1);
170             $dd->query("SELECT
171                     c.column_name as name,
172                     pgd.description as desc
173                 FROM pg_catalog.pg_statio_all_tables as st
174                     inner join pg_catalog.pg_description pgd on (pgd.objoid=st.relid)
175                     inner join information_schema.columns c on (pgd.objsubid=c.ordinal_position and c.table_schema=st.schemaname and c.table_name=st.relname)
176                 WHERE
177                     c.table_schema = 'public' and c.table_name = '{$tn}'
178             ");
179             while($dd->fetch()) {
180                 $desc[$dd->name] = $dd->desc;
181             }
182         }
183         $defs =  $dd->getDatabaseConnection()->tableInfo($tn);
184         // add descriptions?
185         foreach($defs as $i=>$c) {
186             $defs[$i]['desc'] = isset($desc[$c['name']]) ? $desc[$c['name']] : '';
187         }
188         $cache[$tn]= $defs;
189      
190         return $cache[$tn];
191     }
192     
193 //    function dumpTable($tn)
194 //    {
195 //        $roo = HTML_FlexyFramework::get()->page;
196 //        
197 //        if(empty($tn)){
198 //            return;
199 //        }
200 //        
201 //        $do = DB_DataObject::factory($tn);
202 //        if (!is_a($do,'DB_DataObject')) {
203 //            return;
204 //        }
205 //        
206 //        $dsn = HTML_FlexyFramework::get()->database;
207 //        
208 //        $database = explode('@', $dsn);
209 //        
210 //        $ui = str_replace('mysql://', '', $database[0]);
211 //        
212 //        $user = array_shift(explode(':', $ui));
213 //        $pw = array_pop(explode(':', $ui));
214 //        
215 //        $host = array_shift(explode('/', $database[1]));
216 //        $dn = array_pop(explode('/', $database[1]));
217 //        
218 //        $cmd = "mysqldump -u{$user} ";
219 //        if(!empty($pw)){
220 //            $cmd .= "-p{$pw} ";
221 //        }
222 //        
223 //        $cmd .= "--no-create-info summit {$tn}";
224 //        
225 //        require_once 'System.php';
226 //            
227 //        $tmpdir  = System::mktemp("-d dump");
228 //
229 //        $path = $tmpdir . '/' . $tn . '.sql';
230 //        
231 //        ob_start();
232 //        
233 //        passthru($cmd);
234 //        
235 //        $data = ob_get_contents();
236 //        
237 //        ob_end_clean();
238 //        
239 //        file_put_contents($path, $data);
240 //        
241 //        header('Content-Description: File Transfer');
242 //        header ('Content-Type: application/octet-stream');
243 //        header("Content-Disposition: attachment; filename=\"".basename($path)."\";" );
244 //        header("Expires: 0");
245 //        header("Cache-Control: must-revalidate, post-check=0,pre-check=0");
246 //        header("Pragma: public");
247 //        header('Content-Length: ' . filesize($path));
248 //        
249 //        @ob_clean();
250 //        flush();
251 //        readfile($path);
252 //        
253 //        exit;
254 //    }
255     
256     function dumpDatabase()
257     {
258         $roo = HTML_FlexyFramework::get()->page;
259         
260         $dsn = HTML_FlexyFramework::get()->database;
261         
262         $database = explode('@', $dsn);
263         
264         $ui = str_replace('mysql://', '', $database[0]);
265         
266         $user = array_shift(explode(':', $ui));
267         $pw = array_pop(explode(':', $ui));
268         
269         $host = array_shift(explode('/', $database[1]));
270         $dn = array_pop(explode('/', $database[1]));
271         
272         $cmd = "mysqldump -u{$user} ";
273         if(!empty($pw)){
274             $cmd .= "-p{$pw} ";
275         }
276         
277         $cmd .= "--extended-insert=FALSE --no-create-info {$dn}";
278         
279         require_once 'System.php';
280             
281         $tmpdir  = System::mktemp("-d dump");
282
283         $path = $tmpdir . '/' . $dn . '.sql';
284         
285         ob_start();
286         
287         passthru($cmd);
288         
289         $data = ob_get_contents();
290         
291         ob_end_clean();
292         
293         file_put_contents($path, $data);
294         
295         header('Content-Description: File Transfer');
296         header ('Content-Type: application/octet-stream');
297         header("Content-Disposition: attachment; filename=\"".basename($path)."\";" );
298         header("Expires: 0");
299         header("Cache-Control: must-revalidate, post-check=0,pre-check=0");
300         header("Pragma: public");
301         header('Content-Length: ' . filesize($path));
302         
303         @ob_clean();
304         flush();
305         readfile($path);
306         
307         exit;
308     }
309     
310 }