Builder/Provider/Database/generate.js
[app.Builder.js] / Builder / Provider / Database / generate.js
1 //<script type="text/javascript">
2
3 /**
4  * 
5  * Let's see if libgda can be used to generate our Readers for roo...
6  * 
7  * Concept - conect to database..
8  * 
9  * list tables
10  * 
11  * extra schemas..
12  * 
13  * write readers..
14  * 
15  * 
16  */
17 Gda  = imports.gi.Gda;
18 GObject = imports.gi.GObject;
19
20 GLib = imports.gi.GLib;
21
22 console = imports['../../../console.js'];
23 File = imports['../../../File.js'].File;
24 Gda.init();
25
26 var prov = Gda.Config.list_providers ();
27 //print(prov.dump_as_string());
28 var args = Array.prototype.slice.call(Seed.argv);
29 args.shift();args.shift();// remove first 2
30 if (args.length < 1) {
31     var sample = {
32         DB_NAME : "XXX",
33         USERNAME : "YYY",
34         PASSWORD: "ZZZ",
35         INI : "/path/to/mydb.ini",
36     }
37     print("Usage : seed generate.js  '" + JSON.stringify(sample) +"'");
38     Seed.quit();
39 }
40 var cfg = JSON.parse(args[0]);
41
42 var   cnc = Gda.Connection.open_from_string ("MySQL", "DB_NAME=" + cfg.DB_NAME, 
43                                               "USERNAME=" + cfg.USERNAME + ';PASSWORD=' + cfg.PASSWORD,
44                                               Gda.ConnectionOptions.NONE, null);
45
46
47
48                                               
49
50  
51 Gda.DataSelect.prototype.fetchAll = function()
52 {
53     var cols = [];
54     
55     for (var i =0;i < this.get_n_columns(); i++) {
56         cols.push(this.get_column_name(i));
57     }
58     //console.dump(cols);
59     var iter = this.create_iter();
60     var res = [];
61     while (iter.move_next()) {
62         if (cols.length == 1) {
63             res.push(iter.get_value_at(0).get_string());
64             continue;
65         }
66         var add = { };
67         
68         cols.forEach(function(n,i) {
69            var val = iter.get_value_at(i);
70            var type = GObject.type_name(val.g_type) ;
71            var vs = type == 'GdaBlob' ? val.value.to_string(1024) : val.value;
72          //  print(n + " : TYPE: " + GObject.type_name(val.g_type) + " : " + vs);
73             //print (n + '=' + iter.get_value_at(i).value);
74             add[n] = vs;
75         });
76         
77         res.push(add);
78         
79     }
80     return res;
81
82 }
83
84 var map = {
85     'date' : 'date',
86     'datetime' : 'string',
87     'int' : 'int',
88     'bigint' : 'int',
89     'char' : 'int',
90     'tinyint' : 'int',
91     'decimal' : 'float',
92     'float' : 'float',
93     'varchar' : 'string',
94     'text' : 'string',
95     'longtext' : 'string',
96     'mediumtext' : 'string',
97     'enum' : 'string',
98     
99     
100 }
101
102 var ini = { }
103
104 function readIni(fn)
105 {
106     var key_file = GLib.key_file_new();
107     if (!GLib.key_file_load_from_file (key_file, fn , GLib.KeyFileFlags.NONE )) {
108         return;
109     }
110    
111     var groups = GLib.key_file_get_groups(key_file);
112     groups.forEach(function(g) {
113         ini[g] = {}
114            
115         var keys = GLib.key_file_get_keys(key_file,g);
116         keys.forEach(function(k) {
117             ini[g][k] = GLib.key_file_get_value(key_file,g,k);
118         })
119     })
120     
121 }
122 if (File.isFile(cfg.INI)) {
123     if (cfg.INI.match(/links\.ini$/)) {
124         readIni(cfg.INI);
125     } else {
126         readIni(cfg.INI.replace(/\.ini$/, ".links.ini"));
127     }
128 }
129
130 if (File.isDirectory(cfg.INI)) {
131         
132
133     //--- load ini files..
134     // this is very specific.
135     var dirs = File.list( GLib.get_home_dir() + '/gitlive').filter( 
136         function(e) { return e.match(/^Pman/); }
137     );
138     
139     dirs.forEach(function(d) {
140         // this currently misses the web.*/Pman/XXXX/DataObjects..
141         var path = GLib.get_home_dir() + '/gitlive/' + d + '/DataObjects';
142         if (!File.isDirectory(path)) {
143             path = GLib.get_home_dir() + '/gitlive/' + d + '/Pman/DataObjects';
144         }
145         if (!File.isDirectory(path)) {
146             return; //skip
147         }
148         var inis = File.list(path).filter(
149             function(e) { return e.match(/\.links\.ini$/); }
150         );
151         if (!inis.length) {
152             return;
153         }
154         
155         inis.forEach(function(i) {
156             readIni(path + '/' + i); 
157             
158         })
159
160         
161         
162     });
163 }
164  //console.dump(ini);
165
166
167  //Seed.quit();
168
169 //GLib.key_file_load_from_file (key_file, String file, KeyFileFlags flags) : Boolean
170
171
172
173
174
175
176
177
178
179
180
181 var tables = Gda.execute_select_command(cnc, "SHOW TABLES").fetchAll();
182 var readers = [];
183 tables.forEach(function(table) {
184     //print(table);
185     var schema = Gda.execute_select_command(cnc, "DESCRIBE `" + table+'`').fetchAll();
186     var reader = []; 
187     schema.forEach(function(e)  {
188         var type = e.Type.match(/([^(]+)\(([^\)]+)\)/);
189         var row  = { }; 
190         if (type) {
191             e.Type = type[1];
192             e.Size = type[2];
193         }
194         
195         
196         
197         row.name = e.Field;
198         
199         
200         if (typeof(map[e.Type]) == 'undefined') {
201            console.dump(e);
202            throw {
203                 name: "ArgumentError", 
204                 message: "Unknown mapping for type : " + e.Type
205             };
206         }
207         row.type = map[e.Type];
208         if (row.type == 'date') {
209             row.dateFormat = 'Y-m-d';
210         }
211         reader.push(row);
212         
213     });
214     print(JSON.stringify(reader,null,4));
215     readers.push({
216         table : table ,
217         reader :  reader,
218         oreader : JSON.parse(JSON.stringify(reader)) // dupe it..
219     });
220     
221     //console.dump(schema );
222     
223      
224 });
225
226
227
228 // merge in the linked tables..
229 readers.forEach(function(reader) {
230     if (typeof(ini[reader.table]) == 'undefined') {
231      
232         return;
233     }
234    print("OVERLAY - " + reader.table);
235     // we have a map..
236     for (var col in ini[reader.table]) {
237         var kv = ini[reader.table][col].split(':');
238         var add = readers.filter(function(r) { return r.table == kv[0] })[0];
239         add.oreader.forEach(function(or) {
240             reader.reader.push({
241                 name : col + '_' + or.name,
242                 type : or.type
243             });
244         });
245              
246     };
247     
248     
249 });
250
251 readers.forEach(function(reader) {
252     delete reader.oreader;
253 });
254
255  
256
257
258
259 //print(JSON.stringify(readers, null, 4));
260
261 readers.forEach(function(reader) {
262     
263
264     var dir = GLib.get_home_dir() + '/.Builder/Roo.data.JsonReader'; 
265     if (!File.isDirectory(dir)) {
266         File.mkdir(dir);
267     }
268     print("WRITE: " +  dir + '/' + cfg.DB_NAME + '_' + reader.table + '.json');
269     
270                 
271     var jreader = {
272         '|xns' : 'Roo.data',
273         xtype : "JsonReader",
274         totalProperty : "total",
275         root : "data",
276         '*prop' : "reader",
277         id : 'id', // maybe no..
278         '|fields' :  JSON.stringify(reader.reader, null,4)
279     };
280     
281     File.write(
282         dir + '/' + cfg.DB_NAME + '_' + reader.table + '.json',
283         JSON.stringify(jreader, null, 4)
284     )
285     
286     dir = GLib.get_home_dir() + '/.Builder/Roo.GridPanel'; 
287     if (!File.isDirectory(dir)) {
288         File.mkdir(dir);
289     }
290     print("WRITE: " +  dir + '/' + cfg.DB_NAME + '_' + reader.table + '.json');
291     
292       File.write(
293         dir + '/' + cfg.DB_NAME + '_' + reader.table + '.json',
294             
295        
296         JSON.stringify({
297             '|xns' : 'Roo',
298             xtype : "GridPanel",
299             "title": reader.table,
300             "fitToframe": true,
301             "fitContainer": true,
302             "tableName": reader.table,
303             "background": true,
304             "listeners": {
305                 "|activate": "function() {\n    _this.panel = this;\n    if (_this.grid) {\n        _this.grid.footer.onClick('first');\n    }\n}"
306             },
307         
308             "items": [
309                 {
310                     "*prop": "dataSource",
311                     "xtype": "Store",
312                     
313                     "|xns": "Roo.data",
314                     "items": [
315                         
316                         {
317                             "*prop": "proxy",
318                             "xtype": "HttpProxy",
319                             "method": "GET",
320                             "|url": "baseURL + '/Roo/" + reader.table ".php'",
321                             "|xns": "Roo.data"
322                         },
323                         jreader
324                     ]
325                 },
326                 {
327                     "*prop": "footer",
328                     "xtype": "PagingToolbar",
329                     "pageSize": 25,
330                     "displayInfo": true,
331                     "displayMsg": "Displaying " + reader.table + "{0} - {1} of {2}",
332                     "emptyMsg": "No " + reader.table + " found",
333                     "|xns": "Roo"
334                 },
335                 {
336                     "*prop": "toolbar",
337                     "xtype": "Toolbar",
338                     "|xns": "Roo",
339                     "items": [
340                         {
341                             "text": "Add",
342                             "xtype": "Button",
343                             "cls": "x-btn-text-icon",
344                             "|icon": "Roo.rootURL + 'images/default/dd/drop-add.gif'",
345                             "listeners": {
346                                 "|click": "function()\n"+
347                                     "{\n"+
348                                     "   //yourdialog.show( { id : 0 } , function() {\n"+
349                                     "   //  _this.grid.footer.onClick('first');\n"+
350                                     "   //}); \n"+
351                                     "}\n"
352                             },
353                             "|xns": "Roo"
354                         },
355                         {
356                             "text": "Edit",
357                             "xtype": "Button",
358                             "cls": "x-btn-text-icon",
359                             "|icon": "Roo.rootURL + 'images/default/tree/leaf.gif'",
360                             "listeners": {
361                                 "|click": "function()\n"+
362                                     "{\n"+
363                                     "    var s = _this.grid.getSelectionModel().getSelections();\n"+
364                                     "    if (!s.length || (s.length > 1))  {\n"+
365                                     "        Roo.MessageBox.alert(\"Error\", s.length ? \"Select only one Row\" : \"Select a Row\");\n"+
366                                     "        return;\n"+
367                                     "    }\n"+
368                                     "    \n"+
369                                     "    //_this.dialog.show(s[0].data, function() {\n"+
370                                     "    //    _this.grid.footer.onClick('first');\n"+
371                                     "    //   }); \n"+
372                                     "    \n"+
373                                     "}\n" 
374                                 
375                             },
376                             "|xns": "Roo"
377                         },
378                         {
379                             "text": "Delete",
380                             "cls": "x-btn-text-icon",
381                             "|icon": "rootURL + '/Pman/templates/images/trash.gif'",
382                             "xtype": "Button",
383                             "listeners": {
384                                 "|click": "function()\n"+
385                                     "{\n"+
386                                     "   //Pman.genericDelete(_this, _this.grid.tableName); \n"+
387                                     "}\n"+
388                                     "        "
389                             },
390                             "|xns": "Roo"
391                         }
392                     ]
393                 }, // end toolbar
394                 
395                 
396                 
397             
398             
399         }, null, 4)
400     )
401     
402     
403     
404     
405     
406
407 });
408
409
410
411
412