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                 'remoteSort' : true,
329                 '|sortInfo' : '{ direction : \'ASC\', field: \'id\' }',
330                 listeners : {
331                     '|beforeload' : 'function (_self, o)' +
332                     "{\n" +
333                     "    o.params = o.params || {};\n" +
334                     "    // set more here\n" +
335                     "}\n"
336                 },
337                 items : [
338                     {
339                         '*prop' : 'proxy',
340                         'xtype' : 'HttpProxy',
341                         'method' : 'GET',
342                         '|xns' : 'Roo.data',
343                         '|url' : "baseURL + '/Roo/" + table + ".php'",
344                     },
345                     
346                     {
347                         '*prop' : 'reader',
348                         'xtype' : 'JsonReader',
349                         '|xns' : 'Roo.data',
350                         'id' : 'id',
351                         'root' : 'data',
352                         'totalProperty' : 'total',
353                         '|fields' : JSON.stringify(combofields)
354                         
355                     }
356                 ]
357             }
358         ]
359     }
360     
361     
362     
363     
364     //print(JSON.stringify(reader,null,4));
365     readers.push({
366         table : table ,
367         combo : combo,
368         combofields : combofields,
369         reader :  reader,
370         oreader : JSON.parse(JSON.stringify(reader)), // dupe it..
371         colmodel : colmodel,
372         firstTxtCol : firstTxtCol,
373         form : form
374     });
375     
376     //console.dump(schema );
377     
378      
379 });
380
381
382
383 // merge in the linked tables..
384 readers.forEach(function(reader) {
385     if (typeof(ini[reader.table]) == 'undefined') {
386      
387         return;
388     }
389     print("OVERLAY - " + reader.table);
390     // we have a map..
391     for (var col in ini[reader.table]) {
392         var kv = ini[reader.table][col].split(':');
393         
394         
395         var add = readers.filter(function(r) { return r.table == kv[0] })[0];
396         if (!add) {
397             continue;
398         }
399         // merge in data (eg. project_id => project_id_*****
400      
401         add.oreader.forEach(function(or) {
402             reader.reader.push({
403                 name : col + '_' + or.name,
404                 type : or.type
405             });
406         });
407         
408         // col is mapped to something..
409         var combofields = add.combofields;
410         if (add.combofields.length < 2) {
411             continue;
412         }
413         if (typeof(reader.form[col]) == 'undefined') {
414             print("missing linked column " + col);
415             continue;
416         }
417         
418         var combofields_name = add.combofields[1].name;
419         var old =   reader.form[col];
420         reader.form[col] = JSON.parse(JSON.stringify(add.combo)); // clone
421         reader.form[col].queryParam  = 'query[' + combofields_name + ']';// SET WHEN USED
422         reader.form[col].fieldLabel = old.fieldLabel;  // SET WHEN USED
423         reader.form[col].hiddenName = old.name; // SET WHEN USED eg. project_id
424         reader.form[col].displayField = combofields_name; // SET WHEN USED eg. project_id
425         reader.form[col].name  = old.name + '_' + combofields_name; // SET WHEN USED eg. project_id_name
426         reader.form[col].tpl = '<div class="x-grid-cell-text x-btn button"><b>{' + combofields_name +'}</b> </div>'; // SET WHEN USED
427         
428              
429     };
430     
431     
432 });
433
434 //readers.forEach(function(reader) {
435 //    delete reader.oreader;
436 //});
437
438  
439
440
441
442 //print(JSON.stringify(readers, null, 4));
443
444 readers.forEach(function(reader) {
445     
446
447     var dir = GLib.get_home_dir() + '/.Builder/Roo.data.JsonReader'; 
448     if (!File.isDirectory(dir)) {
449         File.mkdir(dir);
450     }
451     
452     // READERS
453     print("WRITE: " +  dir + '/' + cfg.DB_NAME + '_' + reader.table + '.json');
454     
455                 
456     var jreader = {
457         '|xns' : 'Roo.data',
458         xtype : "JsonReader",
459         totalProperty : "total",
460         root : "data",
461         '*prop' : "reader",
462         id : 'id', // maybe no..
463         '|fields' :  JSON.stringify(reader.reader, null,4).replace(/"/g,"'")
464     };
465     
466     File.write(
467         dir + '/' + cfg.DB_NAME + '_' + reader.table + '.json',
468         JSON.stringify(jreader, null, 4)
469     )
470     
471     
472     // GRIDS
473     dir = GLib.get_home_dir() + '/.Builder/Roo.GridPanel'; 
474     if (!File.isDirectory(dir)) {
475         File.mkdir(dir);
476     }
477     
478
479     print("WRITE: " +  dir + '/' + cfg.DB_NAME + '_' + reader.table + '.json');
480     
481     File.write(
482         dir + '/' + cfg.DB_NAME + '_' + reader.table + '.json',
483             
484        
485         JSON.stringify({
486             '|xns' : 'Roo',
487             xtype : "GridPanel",
488             "title": reader.table,
489             "fitToframe": true,
490             "fitContainer": true,
491             "tableName": reader.table,
492             "background": true,
493             "listeners": {
494                 "|activate": "function() {\n    _this.panel = this;\n    if (_this.grid) {\n        _this.grid.footer.onClick('first');\n    }\n}"
495             },
496             "items": [
497                 {
498                     "*prop": "grid",
499                     "xtype": "Grid",
500                     "autoExpandColumn": reader.firstTxtCol,
501                     "loadMask": true,
502                     "listeners": {
503                         "|render": "function() \n" +
504                             "{\n" +
505                             "   _this.grid = this; \n" +
506                             "    //_this.dialog = Pman.Dialog.FILL_IN\n" +
507                             "    if (_this.panel.active) {\n" +
508                             "       this.footer.onClick('first');\n" +
509                             "    }\n" +
510                             "}"
511                     },
512                     "|xns": "Roo.grid",
513
514                     "items": [
515                         {
516                             "*prop": "dataSource",
517                             "xtype": "Store",
518                             
519                             "|xns": "Roo.data",
520                             "items": [
521                                 
522                                 {
523                                     "*prop": "proxy",
524                                     "xtype": "HttpProxy",
525                                     "method": "GET",
526                                     "|url": "baseURL + '/Roo/" + reader.table + ".php'",
527                                     "|xns": "Roo.data"
528                                 },
529                                 jreader
530                             ]
531                         },
532                         {
533                             "*prop": "footer",
534                             "xtype": "PagingToolbar",
535                             "pageSize": 25,
536                             "displayInfo": true,
537                             "displayMsg": "Displaying " + reader.table + "{0} - {1} of {2}",
538                             "emptyMsg": "No " + reader.table + " found",
539                             "|xns": "Roo"
540                         },
541                         {
542                             "*prop": "toolbar",
543                             "xtype": "Toolbar",
544                             "|xns": "Roo",
545                             "items": [
546                                 {
547                                     "text": "Add",
548                                     "xtype": "Button",
549                                     "cls": "x-btn-text-icon",
550                                     "|icon": "Roo.rootURL + 'images/default/dd/drop-add.gif'",
551                                     "listeners": {
552                                         "|click": "function()\n"+
553                                             "{\n"+
554                                             "   //yourdialog.show( { id : 0 } , function() {\n"+
555                                             "   //  _this.grid.footer.onClick('first');\n"+
556                                             "   //}); \n"+
557                                             "}\n"
558                                     },
559                                     "|xns": "Roo.Toolbar"
560                                 },
561                                 {
562                                     "text": "Edit",
563                                     "xtype": "Button",
564                                     "cls": "x-btn-text-icon",
565                                     "|icon": "Roo.rootURL + 'images/default/tree/leaf.gif'",
566                                     "listeners": {
567                                         "|click": "function()\n"+
568                                             "{\n"+
569                                             "    var s = _this.grid.getSelectionModel().getSelections();\n"+
570                                             "    if (!s.length || (s.length > 1))  {\n"+
571                                             "        Roo.MessageBox.alert(\"Error\", s.length ? \"Select only one Row\" : \"Select a Row\");\n"+
572                                             "        return;\n"+
573                                             "    }\n"+
574                                             "    \n"+
575                                             "    //_this.dialog.show(s[0].data, function() {\n"+
576                                             "    //    _this.grid.footer.onClick('first');\n"+
577                                             "    //   }); \n"+
578                                             "    \n"+
579                                             "}\n" 
580                                         
581                                     },
582                                     "|xns": "Roo.Toolbar"
583                                 },
584                                 {
585                                     "text": "Delete",
586                                     "cls": "x-btn-text-icon",
587                                     "|icon": "rootURL + '/Pman/templates/images/trash.gif'",
588                                     "xtype": "Button",
589                                     "listeners": {
590                                         "|click": "function()\n"+
591                                             "{\n"+
592                                             "   //Pman.genericDelete(_this, _this.grid.tableName); \n"+
593                                             "}\n"+
594                                             "        "
595                                     },
596                                     "|xns": "Roo.Toolbar"
597                                 }
598                             ]
599                         }, // end toolbar
600                     ].concat( reader.colmodel)
601                 }
602             ]
603             
604             
605         }, null, 4)
606     )
607     
608     /// FORMS..
609     
610     dir = GLib.get_home_dir() + '/.Builder/Roo.form.Form'; 
611     if (!File.isDirectory(dir)) {
612         File.mkdir(dir);
613     }
614     var formElements = [];
615     for (var k in reader.form) {
616         if (k == 'id') { // should really do primary key testing..
617             continue;
618         }
619         formElements.push(reader.form[k]);
620     }
621     formElements.push(reader.form['id']);
622
623     print("WRITE: " +  dir + '/' + cfg.DB_NAME + '_' + reader.table + '.json');
624     
625     File.write(
626         dir + '/' + cfg.DB_NAME + '_' + reader.table + '.json',
627             
628        
629         JSON.stringify({
630             '|xns' : 'Roo.form',
631             xtype : "Form",
632             listeners : {
633                 "|actioncomplete" : "function(_self,action)\n"+
634                     "{\n"+
635                     "    if (action.type == 'setdata') {\n"+
636                     "       //_this.dialog.el.mask(\"Loading\");\n"+
637                     "       //this.load({ method: 'GET', params: { '_id' : _this.data.id }});\n"+
638                     "       return;\n"+
639                     "    }\n"+
640                     "    if (action.type == 'load') {\n"+
641                     "        _this.dialog.el.unmask();\n"+
642                     "        return;\n"+
643                     "    }\n"+
644                     "    if (action.type =='submit') {\n"+
645                     "    \n"+
646                     "        _this.dialog.el.unmask();\n"+
647                     "        _this.dialog.hide();\n"+
648                     "    \n"+
649                     "         if (_this.callback) {\n"+
650                     "            _this.callback.call(_this, _this.form.getValues());\n"+
651                     "         }\n"+
652                     "         _this.form.reset();\n"+
653                     "         return;\n"+
654                     "    }\n"+
655                     "}\n",
656                 
657                 "|rendered" : "function (form)\n"+
658                     "{\n"+
659                     "    _this.form= form;\n"+
660                     "}\n"
661             },
662             method : "POST",
663             style : "margin:10px;",
664             "|url" : "baseURL + '/Roo/" + reader.table + ".php'",
665             items : formElements
666         }, null, 4)
667     );
668             
669             
670    
671    
672    
673      /// COMBO..
674     
675     dir = GLib.get_home_dir() + '/.Builder/Roo.form.ComboBox'; 
676     if (!File.isDirectory(dir)) {
677         File.mkdir(dir);
678     }
679    
680     print("WRITE: " +  dir + '/' + cfg.DB_NAME + '_' + reader.table + '.json');
681     
682     File.write(
683         dir + '/' + cfg.DB_NAME + '_' + reader.table + '.json',
684             
685        
686         JSON.stringify(reader.combo, null, 4)
687     );
688             
689    
690    
691    
692    
693    
694    
695    
696    
697    
698 });              
699
700
701
702