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