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 print(JSON.stringify(ini, null,4));
165  //console.dump(ini);
166
167
168  //Seed.quit();
169
170 //GLib.key_file_load_from_file (key_file, String file, KeyFileFlags flags) : Boolean
171
172
173
174  
175
176 var tables = Gda.execute_select_command(cnc, "SHOW TABLES").fetchAll();
177 var readers = [];
178 tables.forEach(function(table) {
179     //print(table);
180     var schema = Gda.execute_select_command(cnc, "DESCRIBE `" + table+'`').fetchAll();
181     var reader = []; 
182     var colmodel = []; 
183     var firstTxtCol = '';
184     schema.forEach(function(e)  {
185         var type = e.Type.match(/([^(]+)\(([^\)]+)\)/);
186         var row  = { }; 
187         if (type) {
188             e.Type = type[1];
189             e.Size = type[2];
190         }
191         
192         
193         
194         row.name = e.Field;
195         
196         
197         if (typeof(map[e.Type]) == 'undefined') {
198            console.dump(e);
199            throw {
200                 name: "ArgumentError", 
201                 message: "Unknown mapping for type : " + e.Type
202             };
203         }
204         row.type = map[e.Type];
205         
206         if (row.type == 'string' && !firstTxtCol.length) {
207             firstTxtCol = row.name;
208         }
209         
210         if (row.type == 'date') {
211             row.dateFormat = 'Y-m-d';
212         }
213         reader.push(row);
214         
215         colmodel.push({
216             "xtype": "ColumnModel",
217             "header": row.name,
218             "width":  row.type == 'string' ? 200 : 75,
219             "dataIndex": row.name,
220             "|renderer": row.type != 'date' ? 
221                     "function(v) { return String.format('{0}', v); }" :
222                     "function(v) { return String.format('{0}', v ? v.format('d/M/Y') : ''); }" , // special for date
223             "|xns": "Roo.grid",
224             "*prop": "colModel[]"
225         })
226     });
227     
228     
229     
230     
231     //print(JSON.stringify(reader,null,4));
232     readers.push({
233         table : table ,
234         reader :  reader,
235         oreader : JSON.parse(JSON.stringify(reader)), // dupe it..
236         colmodel : colmodel,
237         firstTxtCol : firstTxtCol
238     });
239     
240     //console.dump(schema );
241     
242      
243 });
244
245
246
247 // merge in the linked tables..
248 readers.forEach(function(reader) {
249     if (typeof(ini[reader.table]) == 'undefined') {
250      
251         return;
252     }
253     print("OVERLAY - " + reader.table);
254     // we have a map..
255     for (var col in ini[reader.table]) {
256         var kv = ini[reader.table][col].split(':');
257         var add = readers.filter(function(r) { return r.table == kv[0] })[0];
258         
259         // merge in data (eg. project_id => project_id_*****
260         
261         add.oreader.forEach(function(or) {
262             reader.reader.push({
263                 name : col + '_' + or.name,
264                 type : or.type
265             });
266         });
267         
268         
269         
270         
271         
272              
273     };
274     
275     
276 });
277
278 //readers.forEach(function(reader) {
279 //    delete reader.oreader;
280 //});
281
282  
283
284
285
286 //print(JSON.stringify(readers, null, 4));
287
288 readers.forEach(function(reader) {
289     
290
291     var dir = GLib.get_home_dir() + '/.Builder/Roo.data.JsonReader'; 
292     if (!File.isDirectory(dir)) {
293         File.mkdir(dir);
294     }
295     
296     // READERS
297     print("WRITE: " +  dir + '/' + cfg.DB_NAME + '_' + reader.table + '.json');
298     
299                 
300     var jreader = {
301         '|xns' : 'Roo.data',
302         xtype : "JsonReader",
303         totalProperty : "total",
304         root : "data",
305         '*prop' : "reader",
306         id : 'id', // maybe no..
307         '|fields' :  JSON.stringify(reader.reader, null,4)
308     };
309     
310     File.write(
311         dir + '/' + cfg.DB_NAME + '_' + reader.table + '.json',
312         JSON.stringify(jreader, null, 4)
313     )
314     
315     
316     // GRIDS
317     dir = GLib.get_home_dir() + '/.Builder/Roo.GridPanel'; 
318     if (!File.isDirectory(dir)) {
319         File.mkdir(dir);
320     }
321     
322
323     print("WRITE: " +  dir + '/' + cfg.DB_NAME + '_' + reader.table + '.json');
324     
325     File.write(
326         dir + '/' + cfg.DB_NAME + '_' + reader.table + '.json',
327             
328        
329         JSON.stringify({
330             '|xns' : 'Roo',
331             xtype : "GridPanel",
332             "title": reader.table,
333             "fitToframe": true,
334             "fitContainer": true,
335             "tableName": reader.table,
336             "background": true,
337             "listeners": {
338                 "|activate": "function() {\n    _this.panel = this;\n    if (_this.grid) {\n        _this.grid.footer.onClick('first');\n    }\n}"
339             },
340             "items": [
341                 {
342                     "*prop": "grid",
343                     "xtype": "Grid",
344                     "autoExpandColumn": reader.firstTxtCol,
345                     "loadMask": true,
346                     "listeners": {
347                         "|render": "function() \n" +
348                             "{\n" +
349                             "   _this.grid = this; \n" +
350                             "    //_this.dialog = Pman.Dialog.FILL_IN\n" +
351                             "    if (_this.panel.active) {\n" +
352                             "       this.footer.onClick('first');\n" +
353                             "    }\n" +
354                             "}"
355                     },
356                     "|xns": "Roo.grid",
357
358                     "items": [
359                         {
360                             "*prop": "dataSource",
361                             "xtype": "Store",
362                             
363                             "|xns": "Roo.data",
364                             "items": [
365                                 
366                                 {
367                                     "*prop": "proxy",
368                                     "xtype": "HttpProxy",
369                                     "method": "GET",
370                                     "|url": "baseURL + '/Roo/" + reader.table + ".php'",
371                                     "|xns": "Roo.data"
372                                 },
373                                 jreader
374                             ]
375                         },
376                         {
377                             "*prop": "footer",
378                             "xtype": "PagingToolbar",
379                             "pageSize": 25,
380                             "displayInfo": true,
381                             "displayMsg": "Displaying " + reader.table + "{0} - {1} of {2}",
382                             "emptyMsg": "No " + reader.table + " found",
383                             "|xns": "Roo"
384                         },
385                         {
386                             "*prop": "toolbar",
387                             "xtype": "Toolbar",
388                             "|xns": "Roo",
389                             "items": [
390                                 {
391                                     "text": "Add",
392                                     "xtype": "Button",
393                                     "cls": "x-btn-text-icon",
394                                     "|icon": "Roo.rootURL + 'images/default/dd/drop-add.gif'",
395                                     "listeners": {
396                                         "|click": "function()\n"+
397                                             "{\n"+
398                                             "   //yourdialog.show( { id : 0 } , function() {\n"+
399                                             "   //  _this.grid.footer.onClick('first');\n"+
400                                             "   //}); \n"+
401                                             "}\n"
402                                     },
403                                     "|xns": "Roo"
404                                 },
405                                 {
406                                     "text": "Edit",
407                                     "xtype": "Button",
408                                     "cls": "x-btn-text-icon",
409                                     "|icon": "Roo.rootURL + 'images/default/tree/leaf.gif'",
410                                     "listeners": {
411                                         "|click": "function()\n"+
412                                             "{\n"+
413                                             "    var s = _this.grid.getSelectionModel().getSelections();\n"+
414                                             "    if (!s.length || (s.length > 1))  {\n"+
415                                             "        Roo.MessageBox.alert(\"Error\", s.length ? \"Select only one Row\" : \"Select a Row\");\n"+
416                                             "        return;\n"+
417                                             "    }\n"+
418                                             "    \n"+
419                                             "    //_this.dialog.show(s[0].data, function() {\n"+
420                                             "    //    _this.grid.footer.onClick('first');\n"+
421                                             "    //   }); \n"+
422                                             "    \n"+
423                                             "}\n" 
424                                         
425                                     },
426                                     "|xns": "Roo"
427                                 },
428                                 {
429                                     "text": "Delete",
430                                     "cls": "x-btn-text-icon",
431                                     "|icon": "rootURL + '/Pman/templates/images/trash.gif'",
432                                     "xtype": "Button",
433                                     "listeners": {
434                                         "|click": "function()\n"+
435                                             "{\n"+
436                                             "   //Pman.genericDelete(_this, _this.grid.tableName); \n"+
437                                             "}\n"+
438                                             "        "
439                                     },
440                                     "|xns": "Roo"
441                                 }
442                             ]
443                         }, // end toolbar
444                     ].concat( reader.colmodel)
445                 }
446             ]
447             
448             
449         }, null, 4)
450     )
451     
452     /// FORMS..
453     
454     dir = GLib.get_home_dir() + '/.Builder/Roo.form.Form'; 
455     if (!File.isDirectory(dir)) {
456         File.mkdir(dir);
457     }
458     
459
460     print("WRITE: " +  dir + '/' + cfg.DB_NAME + '_' + reader.table + '.json');
461     
462     File.write(
463         dir + '/' + cfg.DB_NAME + '_' + reader.table + '.json',
464             
465        
466         JSON.stringify({
467             '|xns' : 'Roo.form',
468             xtype : "Form",
469             listeners : {
470                 "|actioncomplete" : "function(_self,action)\n"+
471                     "{\n"+
472                     "    if (action.type == 'setdata') {\n"+
473                     "       //_this.dialog.el.mask(\"Loading\");\n"+
474                     "       //this.load({ method: 'GET', params: { '_id' : _this.data.id }});\n"+
475                     "       return;\n"+
476                     "    }
477                     "    if (action.type == 'load') {\n"+
478                     "        _this.dialog.el.unmask();\n"+
479                     "        return;\n"+
480                     "    }\n"+
481                     "    if (action.type =='submit') {\n"+
482                     "    \n"+
483                     "        _this.dialog.el.unmask();\n"+
484                     "        _this.dialog.hide();\n"+
485                     "    \n"+
486                     "         if (_this.callback) {\n"+
487                     "            _this.callback.call(_this, _this.form.getValues());\n"+
488                     "         }\n"+
489                     "         _this.form.reset();\n"+
490                     "         return;"\n"+
491                     "    }\n"+
492                     "}\n",
493                 
494                 "|rendered" : "function (form)\n"+
495                     "{\n"+
496                     "    _this.form= form;
497                     "}\n"
498             }
499             method : "POST",
500             style : "margin:10px;",
501             "|url" : "baseURL + '/Roo/" + reader.table + ".php'",
502             items : reader.formElements
503         })
504     );
505             
506             
507                    
508 });              
509
510
511
512