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