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