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  * usage: seed generate.js  '{"DB_NAME":"XXX","USERNAME":"YYY","PASSWORD":"ZZZ","INI":"/path/to/mydb.ini"}'
16  * 
17  */
18 Gda  = imports.gi.Gda;
19 GObject = imports.gi.GObject;
20
21 GLib = imports.gi.GLib;
22
23 console = imports['../../../console.js'];
24 File = imports['../../../File.js'].File;
25 Gda.init();
26
27 var prov = Gda.Config.list_providers ();
28 //print(prov.dump_as_string());
29 var args = Array.prototype.slice.call(Seed.argv);
30 args.shift();args.shift();// remove first 2
31 print(args.length );
32 if (args.length < 1) {
33     var sample = {
34         DB_NAME : "XXX",
35         USERNAME : "YYY",
36         PASSWORD: "ZZZ",
37         INI : "/path/to/mydb.ini",
38     }
39     print("Usage : seed generate.js  '" + JSON.stringify(sample) +"'");
40     Seed.quit();
41 }
42 var cfg = JSON.parse(args[0]);
43
44 var   cnc = Gda.Connection.open_from_string ("MySQL", "DB_NAME=" + cfg.DB_NAME, 
45                                               "USERNAME=" + cfg.USERNAME + ';PASSWORD=' + cfg.PASSWORD,
46                                               Gda.ConnectionOptions.NONE, null);
47
48
49
50                                               
51
52  
53 Gda.DataSelect.prototype.fetchAll = function()
54 {
55     var cols = [];
56     
57     for (var i =0;i < this.get_n_columns(); i++) {
58         cols.push(this.get_column_name(i));
59     }
60     //print(JSON.stringify(cols, null,4));
61     var iter = this.create_iter();
62     var res = [];
63     //print(this.get_n_rows());
64     var _this = this;
65     for (var r = 0; r < this.get_n_rows(); r++) {
66         
67         // single clo..
68         //print("GOT ROW");
69         if (cols.length == 1) {
70             res.push(this.get_value_at(0,r).get_string());
71             continue;
72         }
73         var add = { };
74         
75         cols.forEach(function(n,i) {
76             var val = _this.get_value_at(i,r);
77             var type = GObject.type_name(val.g_type) ;
78             var vs = ['GdaBinary', 'GdaBlob' ].indexOf(type) > -1 ? val.value.to_string(1024) : val.value;
79             //print(n + " : TYPE: " + GObject.type_name(val.g_type) + " : " + vs);
80             //print (n + '=' + iter.get_value_at(i).value);
81             add[n] = vs;
82         });
83         
84         res.push(add);
85         
86     }
87     return res;
88
89 }
90
91 var map = {
92     'date' : 'date',
93     'datetime' : 'string',
94     'int' : 'int',
95     'bigint' : 'int',
96     'char' : 'int',
97     'tinyint' : 'int',
98     'decimal' : 'float',
99     'float' : 'float',
100     'varchar' : 'string',
101     'text' : 'string',
102     'longtext' : 'string',
103     'tinytext' : 'string',
104     'mediumtext' : 'string',
105     'enum' : 'string',
106     'timestamp' : 'number',
107     'blob' : 'text'
108     
109 }
110
111 var ini = { }
112
113 function readIni(fn)
114 {
115     var key_file = new GLib.KeyFile.c_new();
116     if (!key_file.load_from_file (fn , GLib.KeyFileFlags.NONE )) {
117         return;
118     }
119    
120     var groups = key_file.get_groups();
121     groups.forEach(function(g) {
122         ini[g] = {}
123            
124         var keys = key_file.get_keys(g);
125         keys.forEach(function(k) {
126             ini[g][k] = key_file.get_value(g,k);
127         })
128     })
129     
130 }
131 if (File.isFile(cfg.INI)) {
132     if (cfg.INI.match(/links\.ini$/)) {
133         readIni(cfg.INI);
134     } else {
135         readIni(cfg.INI.replace(/\.ini$/, ".links.ini"));
136     }
137 }
138
139 if (File.isDirectory(cfg.INI)) {
140         
141
142     //--- load ini files..
143     // this is very specific.
144     
145     var dirs = File.list( cfg.INI + '/Pman').filter( 
146         function(e) { 
147             if (!File.isDirectory(cfg.INI + '/Pman/' + e + '/DataObjects')) {
148                 return false;
149             }
150             return true;
151         }
152     );
153     
154      
155     dirs.forEach(function(d) {
156         // this currently misses the web.*/Pman/XXXX/DataObjects..
157         var path = cfg.INI + '/Pman/' + d + '/DataObjects';
158          
159         if (!File.isDirectory(path)) {
160             return; //skip
161         }
162         var inis = File.list(path).filter(
163             function(e) { return e.match(/\.links\.ini$/); }
164         );
165         if (!inis.length) {
166             return;
167         }
168         
169         inis.forEach(function(i) {
170             readIni(path + '/' + i); 
171             
172         })
173  
174     });
175     // look at web.XXXX/Pman/XXX/DataObjects/*.ini
176     var inis = File.list(cfg.INI).filter(
177         function(e) { return e.match(/\.links\.ini$/); }
178     )
179     
180      inis.forEach(function(i) {
181         readIni(path + '/' + i); 
182         
183     })
184     
185     
186 }
187 print(JSON.stringify(ini, null,4));
188  //console.dump(ini);
189
190
191  //Seed.quit();
192
193 //GLib.key_file_load_from_file (key_file, String file, KeyFileFlags flags) : Boolean
194
195
196
197  
198
199 var tables = Gda.execute_select_command(cnc, "SHOW TABLES").fetchAll();
200 var readers = [];
201 tables.forEach(function(table) {
202     //print(table);
203     var schema = Gda.execute_select_command(cnc, "DESCRIBE `" + table+'`').fetchAll();
204     var reader = []; 
205     var colmodel = []; 
206     var combofields= [ { name : 'id', type: 'int' } ]; // technically the primary key..
207          
208     var form = {}
209        
210     var firstTxtCol = '';
211     
212     print(JSON.stringify(schema, null,4));
213     
214     schema.forEach(function(e)  {
215         var type = e.Type.match(/([^(]+)\(([^\)]+)\)/);
216         var row  = { }; 
217         if (type) {
218             e.Type = type[1];
219             e.Size = type[2];
220         }
221         
222         
223         
224         row.name = e.Field;
225         
226         
227         if (typeof(map[e.Type]) == 'undefined') {
228            console.dump(e);
229            throw {
230                 name: "ArgumentError", 
231                 message: "Unknown mapping for type : " + e.Type
232             };
233         }
234         row.type = map[e.Type];
235         
236         if (row.type == 'string' && !firstTxtCol.length) {
237             firstTxtCol = row.name;
238         }
239         
240         if (row.type == 'date') {
241             row.dateFormat = 'Y-m-d';
242         }
243         reader.push(row);
244         
245         if (combofields.length == 1 && row.type == 'string') {
246             combofields.push(row);
247         }
248         
249         
250         var title = row.name.replace(/_id/, '').replace(/_/g, ' ');
251         title  = title[0].toUpperCase() + title.substring(1);
252         
253         colmodel.push({
254             "xtype": "ColumnModel",
255             "header": title,
256             "width":  row.type == 'string' ? 200 : 75,
257             "dataIndex": row.name,
258             "|renderer": row.type != 'date' ? 
259                     "function(v) { return String.format('{0}', v); }" :
260                     "function(v) { return String.format('{0}', v ? v.format('d/M/Y') : ''); }" , // special for date
261             "|xns": "Roo.grid",
262             "*prop": "colModel[]"
263         });
264         var xtype = 'TextField';
265         if (row.type == 'number') {
266             xtype = 'NumberField';
267         }
268         if (row.type == 'date') {
269             xtype = 'DateField';
270         }
271         if (e.Type == 'text') {
272             xtype = 'TextArea';
273         }
274         if (e.name == 'id') {
275             xtype = 'Hidden';
276         }
277         // what about booleans.. -> checkboxes..
278         
279         
280         
281         form[row.name] = {
282             fieldLabel : title,
283             name : row.name,
284             width : row.type == 'string' ? 200 : 75,
285             '|xns' : 'Roo.form',
286             xtype : xtype
287         }
288         if (xtype == 'TextArea') {
289             form[row.name].height = 100;
290         }
291         
292         
293     });
294     
295     var combo = {
296         '|xns' : 'Roo.form',
297         xtype: 'ComboBox',
298         allowBlank : 'false',
299         editable : 'false',
300         emptyText : 'Select ' + table,
301         forceSelection : true,
302         listWidth : 400,
303         loadingText: 'Searching...',
304         minChars : 2,
305         pageSize : 20,
306         qtip: 'Select ' + table,
307         selectOnFocus: true,
308         triggerAction : 'all',
309         typeAhead: true,
310         
311         width: 300,
312         
313         
314         
315         tpl : '<div class="x-grid-cell-text x-btn button"><b>{name}</b> </div>', // SET WHEN USED
316         queryParam : '',// SET WHEN USED
317         fieldLabel : table,  // SET WHEN USED
318         valueField : 'id',
319         displayField : '', // SET WHEN USED eg. project_id_name
320         hiddenName : '', // SET WHEN USED eg. project_id
321         name : '', // SET WHEN USED eg. project_id_name
322         items : [
323             {
324                     
325                 '*prop' : 'store',
326                 'xtype' : 'Store',
327                 '|xns' : 'Roo.data',
328                 listeners : {
329                     '|beforeload' : 'function (_self, o)' +
330                     "{\n" +
331                     "    o.params = o.params || {};\n" +
332                     "    // set more here\n" +
333                     "}\n"
334                 },
335                 items : [
336                     {
337                         '*prop' : 'proxy',
338                         'xtype' : 'HttpProxy',
339                         'method' : 'GET',
340                         '|xns' : 'Roo.data',
341                         '|url' : "baseURL + '/Roo/" + table + ".php'",
342                     },
343                     
344                     {
345                         '*prop' : 'reader',
346                         'xtype' : 'JsonReader',
347                         '|xns' : 'Roo.data',
348                         'id' : 'id',
349                         'root' : 'data',
350                         'totalProperty' : 'total',
351                         '|fields' : JSON.stringify(combofields)
352                         
353                     }
354                 ]
355             }
356         ]
357     }
358     
359     
360     
361     
362     //print(JSON.stringify(reader,null,4));
363     readers.push({
364         table : table ,
365         combo : combo,
366         combofields : combofields,
367         reader :  reader,
368         oreader : JSON.parse(JSON.stringify(reader)), // dupe it..
369         colmodel : colmodel,
370         firstTxtCol : firstTxtCol,
371         form : form
372     });
373     
374     //console.dump(schema );
375     
376      
377 });
378
379
380
381 // merge in the linked tables..
382 readers.forEach(function(reader) {
383     if (typeof(ini[reader.table]) == 'undefined') {
384      
385         return;
386     }
387     print("OVERLAY - " + reader.table);
388     // we have a map..
389     for (var col in ini[reader.table]) {
390         var kv = ini[reader.table][col].split(':');
391         
392         
393         var add = readers.filter(function(r) { return r.table == kv[0] })[0];
394         if (!add) {
395             continue;
396         }
397         // merge in data (eg. project_id => project_id_*****
398      
399         add.oreader.forEach(function(or) {
400             reader.reader.push({
401                 name : col + '_' + or.name,
402                 type : or.type
403             });
404         });
405         
406         // col is mapped to something..
407         var combofields = add.combofields;
408         if (add.combofields.length < 2) {
409             continue;
410         }
411         if (typeof(reader.form[col]) == 'undefined') {
412             print("missing linked column " + col);
413             continue;
414         }
415         
416         var combofields_name = add.combofields[1].name;
417         var old =   reader.form[col];
418         reader.form[col] = JSON.parse(JSON.stringify(add.combo)); // clone
419         reader.form[col].queryParam  = 'query[' + combofields_name + ']';// SET WHEN USED
420         reader.form[col].fieldLabel = old.fieldLabel;  // SET WHEN USED
421         reader.form[col].hiddenName = old.name; // SET WHEN USED eg. project_id
422         reader.form[col].displayField = combofields_name; // SET WHEN USED eg. project_id
423         reader.form[col].name  = old.name + '_' + combofields_name; // SET WHEN USED eg. project_id_name
424         reader.form[col].tpl = '<div class="x-grid-cell-text x-btn button"><b>{' + combofields_name +'}</b> </div>'; // SET WHEN USED
425         
426              
427     };
428     
429     
430 });
431
432 //readers.forEach(function(reader) {
433 //    delete reader.oreader;
434 //});
435
436  
437
438
439
440 //print(JSON.stringify(readers, null, 4));
441
442 readers.forEach(function(reader) {
443     
444
445     var dir = GLib.get_home_dir() + '/.Builder/Roo.data.JsonReader'; 
446     if (!File.isDirectory(dir)) {
447         File.mkdir(dir);
448     }
449     
450     // READERS
451     print("WRITE: " +  dir + '/' + cfg.DB_NAME + '_' + reader.table + '.json');
452     
453                 
454     var jreader = {
455         '|xns' : 'Roo.data',
456         xtype : "JsonReader",
457         totalProperty : "total",
458         root : "data",
459         '*prop' : "reader",
460         id : 'id', // maybe no..
461         '|fields' :  JSON.stringify(reader.reader, null,4).replace(/"/g,"'")
462     };
463     
464     File.write(
465         dir + '/' + cfg.DB_NAME + '_' + reader.table + '.json',
466         JSON.stringify(jreader, null, 4)
467     )
468     
469     
470     // GRIDS
471     dir = GLib.get_home_dir() + '/.Builder/Roo.GridPanel'; 
472     if (!File.isDirectory(dir)) {
473         File.mkdir(dir);
474     }
475     
476
477     print("WRITE: " +  dir + '/' + cfg.DB_NAME + '_' + reader.table + '.json');
478     
479     File.write(
480         dir + '/' + cfg.DB_NAME + '_' + reader.table + '.json',
481             
482        
483         JSON.stringify({
484             '|xns' : 'Roo',
485             xtype : "GridPanel",
486             "title": reader.table,
487             "fitToframe": true,
488             "fitContainer": true,
489             "tableName": reader.table,
490             "background": true,
491             "listeners": {
492                 "|activate": "function() {\n    _this.panel = this;\n    if (_this.grid) {\n        _this.grid.footer.onClick('first');\n    }\n}"
493             },
494             "items": [
495                 {
496                     "*prop": "grid",
497                     "xtype": "Grid",
498                     "autoExpandColumn": reader.firstTxtCol,
499                     "loadMask": true,
500                     "listeners": {
501                         "|render": "function() \n" +
502                             "{\n" +
503                             "   _this.grid = this; \n" +
504                             "    //_this.dialog = Pman.Dialog.FILL_IN\n" +
505                             "    if (_this.panel.active) {\n" +
506                             "       this.footer.onClick('first');\n" +
507                             "    }\n" +
508                             "}"
509                     },
510                     "|xns": "Roo.grid",
511
512                     "items": [
513                         {
514                             "*prop": "dataSource",
515                             "xtype": "Store",
516                             
517                             "|xns": "Roo.data",
518                             "items": [
519                                 
520                                 {
521                                     "*prop": "proxy",
522                                     "xtype": "HttpProxy",
523                                     "method": "GET",
524                                     "|url": "baseURL + '/Roo/" + reader.table + ".php'",
525                                     "|xns": "Roo.data"
526                                 },
527                                 jreader
528                             ]
529                         },
530                         {
531                             "*prop": "footer",
532                             "xtype": "PagingToolbar",
533                             "pageSize": 25,
534                             "displayInfo": true,
535                             "displayMsg": "Displaying " + reader.table + "{0} - {1} of {2}",
536                             "emptyMsg": "No " + reader.table + " found",
537                             "|xns": "Roo"
538                         },
539                         {
540                             "*prop": "toolbar",
541                             "xtype": "Toolbar",
542                             "|xns": "Roo",
543                             "items": [
544                                 {
545                                     "text": "Add",
546                                     "xtype": "Button",
547                                     "cls": "x-btn-text-icon",
548                                     "|icon": "Roo.rootURL + 'images/default/dd/drop-add.gif'",
549                                     "listeners": {
550                                         "|click": "function()\n"+
551                                             "{\n"+
552                                             "   //yourdialog.show( { id : 0 } , function() {\n"+
553                                             "   //  _this.grid.footer.onClick('first');\n"+
554                                             "   //}); \n"+
555                                             "}\n"
556                                     },
557                                     "|xns": "Roo"
558                                 },
559                                 {
560                                     "text": "Edit",
561                                     "xtype": "Button",
562                                     "cls": "x-btn-text-icon",
563                                     "|icon": "Roo.rootURL + 'images/default/tree/leaf.gif'",
564                                     "listeners": {
565                                         "|click": "function()\n"+
566                                             "{\n"+
567                                             "    var s = _this.grid.getSelectionModel().getSelections();\n"+
568                                             "    if (!s.length || (s.length > 1))  {\n"+
569                                             "        Roo.MessageBox.alert(\"Error\", s.length ? \"Select only one Row\" : \"Select a Row\");\n"+
570                                             "        return;\n"+
571                                             "    }\n"+
572                                             "    \n"+
573                                             "    //_this.dialog.show(s[0].data, function() {\n"+
574                                             "    //    _this.grid.footer.onClick('first');\n"+
575                                             "    //   }); \n"+
576                                             "    \n"+
577                                             "}\n" 
578                                         
579                                     },
580                                     "|xns": "Roo"
581                                 },
582                                 {
583                                     "text": "Delete",
584                                     "cls": "x-btn-text-icon",
585                                     "|icon": "rootURL + '/Pman/templates/images/trash.gif'",
586                                     "xtype": "Button",
587                                     "listeners": {
588                                         "|click": "function()\n"+
589                                             "{\n"+
590                                             "   //Pman.genericDelete(_this, _this.grid.tableName); \n"+
591                                             "}\n"+
592                                             "        "
593                                     },
594                                     "|xns": "Roo"
595                                 }
596                             ]
597                         }, // end toolbar
598                     ].concat( reader.colmodel)
599                 }
600             ]
601             
602             
603         }, null, 4)
604     )
605     
606     /// FORMS..
607     
608     dir = GLib.get_home_dir() + '/.Builder/Roo.form.Form'; 
609     if (!File.isDirectory(dir)) {
610         File.mkdir(dir);
611     }
612     var formElements = [];
613     for (var k in reader.form) {
614         if (k == 'id') { // should really do primary key testing..
615             continue;
616         }
617         formElements.push(reader.form[k]);
618     }
619     formElements.push(reader.form['id']);
620
621     print("WRITE: " +  dir + '/' + cfg.DB_NAME + '_' + reader.table + '.json');
622     
623     File.write(
624         dir + '/' + cfg.DB_NAME + '_' + reader.table + '.json',
625             
626        
627         JSON.stringify({
628             '|xns' : 'Roo.form',
629             xtype : "Form",
630             listeners : {
631                 "|actioncomplete" : "function(_self,action)\n"+
632                     "{\n"+
633                     "    if (action.type == 'setdata') {\n"+
634                     "       //_this.dialog.el.mask(\"Loading\");\n"+
635                     "       //this.load({ method: 'GET', params: { '_id' : _this.data.id }});\n"+
636                     "       return;\n"+
637                     "    }\n"+
638                     "    if (action.type == 'load') {\n"+
639                     "        _this.dialog.el.unmask();\n"+
640                     "        return;\n"+
641                     "    }\n"+
642                     "    if (action.type =='submit') {\n"+
643                     "    \n"+
644                     "        _this.dialog.el.unmask();\n"+
645                     "        _this.dialog.hide();\n"+
646                     "    \n"+
647                     "         if (_this.callback) {\n"+
648                     "            _this.callback.call(_this, _this.form.getValues());\n"+
649                     "         }\n"+
650                     "         _this.form.reset();\n"+
651                     "         return;\n"+
652                     "    }\n"+
653                     "}\n",
654                 
655                 "|rendered" : "function (form)\n"+
656                     "{\n"+
657                     "    _this.form= form;\n"+
658                     "}\n"
659             },
660             method : "POST",
661             style : "margin:10px;",
662             "|url" : "baseURL + '/Roo/" + reader.table + ".php'",
663             items : formElements
664         }, null, 4)
665     );
666             
667             
668    
669    
670    
671      /// COMBO..
672     
673     dir = GLib.get_home_dir() + '/.Builder/Roo.form.ComboBox'; 
674     if (!File.isDirectory(dir)) {
675         File.mkdir(dir);
676     }
677    
678     print("WRITE: " +  dir + '/' + cfg.DB_NAME + '_' + reader.table + '.json');
679     
680     File.write(
681         dir + '/' + cfg.DB_NAME + '_' + reader.table + '.json',
682             
683        
684         JSON.stringify(reader.combo, null, 4)
685     );
686             
687    
688    
689    
690    
691    
692    
693    
694    
695    
696 });              
697
698
699
700