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 (row.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         if (xtype == 'Hidden') {
300             delete form[row.name].fieldLabel;
301             delete form[row.name].width;
302         }
303         
304     });
305     
306     var combo = {
307         '|xns' : 'Roo.form',
308         xtype: 'ComboBox',
309         allowBlank : 'false',
310         editable : 'false',
311         emptyText : 'Select ' + table,
312         forceSelection : true,
313         listWidth : 400,
314         loadingText: 'Searching...',
315         minChars : 2,
316         pageSize : 20,
317         qtip: 'Select ' + table,
318         selectOnFocus: true,
319         triggerAction : 'all',
320         typeAhead: true,
321         
322         width: 300,
323         
324         
325         
326         tpl : '<div class="x-grid-cell-text x-btn button"><b>{name}</b> </div>', // SET WHEN USED
327         queryParam : '',// SET WHEN USED
328         fieldLabel : table,  // SET WHEN USED
329         valueField : 'id',
330         displayField : '', // SET WHEN USED eg. project_id_name
331         hiddenName : '', // SET WHEN USED eg. project_id
332         name : '', // SET WHEN USED eg. project_id_name
333         items : [
334             {
335                     
336                 '*prop' : 'store',
337                 'xtype' : 'Store',
338                 '|xns' : 'Roo.data',
339                 'remoteSort' : true,
340                 '|sortInfo' : '{ direction : \'ASC\', field: \'id\' }',
341                 listeners : {
342                     '|beforeload' : 'function (_self, o)' +
343                     "{\n" +
344                     "    o.params = o.params || {};\n" +
345                     "    // set more here\n" +
346                     "}\n"
347                 },
348                 items : [
349                     {
350                         '*prop' : 'proxy',
351                         'xtype' : 'HttpProxy',
352                         'method' : 'GET',
353                         '|xns' : 'Roo.data',
354                         '|url' : "baseURL + '/Roo/" + table + ".php'",
355                     },
356                     
357                     {
358                         '*prop' : 'reader',
359                         'xtype' : 'JsonReader',
360                         '|xns' : 'Roo.data',
361                         'id' : 'id',
362                         'root' : 'data',
363                         'totalProperty' : 'total',
364                         '|fields' : JSON.stringify(combofields)
365                         
366                     }
367                 ]
368             }
369         ]
370     }
371     
372     
373     
374     
375     //print(JSON.stringify(reader,null,4));
376     readers.push({
377         table : table ,
378         combo : combo,
379         combofields : combofields,
380         reader :  reader,
381         oreader : JSON.parse(JSON.stringify(reader)), // dupe it..
382         colmodel : colmodel,
383         firstTxtCol : firstTxtCol,
384         form : form
385     });
386     
387     //console.dump(schema );
388     
389      
390 });
391
392
393
394 // merge in the linked tables..
395 readers.forEach(function(reader) {
396     if (typeof(ini[reader.table]) == 'undefined') {
397      
398         return;
399     }
400     print("OVERLAY - " + reader.table);
401     // we have a map..
402     for (var col in ini[reader.table]) {
403         var kv = ini[reader.table][col].split(':');
404         
405         
406         var add = readers.filter(function(r) { return r.table == kv[0] })[0];
407         if (!add) {
408             continue;
409         }
410         // merge in data (eg. project_id => project_id_*****
411      
412         add.oreader.forEach(function(or) {
413             reader.reader.push({
414                 name : col + '_' + or.name,
415                 type : or.type
416             });
417         });
418         
419         // col is mapped to something..
420         var combofields = add.combofields;
421         if (add.combofields.length < 2) {
422             continue;
423         }
424         if (typeof(reader.form[col]) == 'undefined') {
425             print (JSON.stringify(reader.form, null,4));
426             print("missing linked column " + col);
427             continue;
428         }
429         
430         var combofields_name = add.combofields[1].name;
431         var old =   reader.form[col];
432         reader.form[col] = JSON.parse(JSON.stringify(add.combo)); // clone
433         reader.form[col].queryParam  = 'query[' + combofields_name + ']';// SET WHEN USED
434         reader.form[col].fieldLabel = old.fieldLabel;  // SET WHEN USED
435         reader.form[col].hiddenName = old.name; // SET WHEN USED eg. project_id
436         reader.form[col].displayField = combofields_name; // SET WHEN USED eg. project_id
437         reader.form[col].name  = old.name + '_' + combofields_name; // SET WHEN USED eg. project_id_name
438         reader.form[col].tpl = '<div class="x-grid-cell-text x-btn button"><b>{' + combofields_name +'}</b> </div>'; // SET WHEN USED
439         
440              
441     };
442     
443     
444 });
445
446 //readers.forEach(function(reader) {
447 //    delete reader.oreader;
448 //});
449
450  
451
452
453
454 //print(JSON.stringify(readers, null, 4));
455
456 readers.forEach(function(reader) {
457     
458
459     var dir = GLib.get_home_dir() + '/.Builder/Roo.data.JsonReader'; 
460     if (!File.isDirectory(dir)) {
461         File.mkdir(dir);
462     }
463     
464     // READERS
465     print("WRITE: " +  dir + '/' + cfg.DBNAME + '_' + reader.table + '.json');
466     
467                 
468     var jreader = {
469         '|xns' : 'Roo.data',
470         xtype : "JsonReader",
471         totalProperty : "total",
472         root : "data",
473         '*prop' : "reader",
474         id : 'id', // maybe no..
475         remoteSort : true,
476         '|sortInfo' : "{ field : '" + reader.firstTxtCol  +  "', direction: 'ASC' }", 
477         '|fields' :  JSON.stringify(reader.reader, null,4).replace(/"/g,"'")
478     };
479     
480     File.write(
481         dir + '/' + cfg.DBNAME + '_' + reader.table + '.json',
482         JSON.stringify(jreader, null, 4)
483     )
484     
485     
486     // GRIDS
487     dir = GLib.get_home_dir() + '/.Builder/Roo.GridPanel'; 
488     if (!File.isDirectory(dir)) {
489         File.mkdir(dir);
490     }
491     
492
493     print("WRITE: " +  dir + '/' + cfg.DBNAME + '_' + reader.table + '.json');
494     
495     File.write(
496         dir + '/' + cfg.DBNAME + '_' + reader.table + '.json',
497             
498        
499         JSON.stringify({
500             '|xns' : 'Roo',
501             xtype : "GridPanel",
502             "title": reader.table,
503             "fitToframe": true,
504             "fitContainer": true,
505             "tableName": reader.table,
506             "background": true,
507             "listeners": {
508                 "|activate": "function() {\n    _this.panel = this;\n    if (_this.grid) {\n        _this.grid.footer.onClick('first');\n    }\n}"
509             },
510             "items": [
511                 {
512                     "*prop": "grid",
513                     "xtype": "Grid",
514                     "autoExpandColumn": reader.firstTxtCol,
515                     "loadMask": true,
516                     "listeners": {
517                         "|render": "function() \n" +
518                             "{\n" +
519                             "    _this.grid = this; \n" +
520                             "    //_this.dialog = Pman.Dialog.FILL_IN\n" +
521                             "    if (_this.panel.active) {\n" +
522                             "       this.footer.onClick('first');\n" +
523                             "    }\n" +
524                             "}"
525                     },
526                     "|xns": "Roo.grid",
527
528                     "items": [
529                         {
530                             "*prop": "dataSource",
531                             "xtype": "Store",
532                             
533                             "|xns": "Roo.data",
534                             "items": [
535                                 
536                                 {
537                                     "*prop": "proxy",
538                                     "xtype": "HttpProxy",
539                                     "method": "GET",
540                                     "|url": "baseURL + '/Roo/" + reader.table + ".php'",
541                                     "|xns": "Roo.data"
542                                 },
543                                 jreader
544                             ]
545                         },
546                         {
547                             "*prop": "footer",
548                             "xtype": "PagingToolbar",
549                             "pageSize": 25,
550                             "displayInfo": true,
551                             "displayMsg": "Displaying " + reader.table + "{0} - {1} of {2}",
552                             "emptyMsg": "No " + reader.table + " found",
553                             "|xns": "Roo"
554                         },
555                         {
556                             "*prop": "toolbar",
557                             "xtype": "Toolbar",
558                             "|xns": "Roo",
559                             "items": [
560                                 {
561                                     "text": "Add",
562                                     "xtype": "Button",
563                                     "cls": "x-btn-text-icon",
564                                     "|icon": "Roo.rootURL + 'images/default/dd/drop-add.gif'",
565                                     "listeners": {
566                                         "|click": "function()\n"+
567                                             "{\n"+
568                                             "    if (!_this.dialog) return;\n" +
569                                             "    _this.dialog.show( { id : 0 } , function() {\n"+
570                                             "        _this.grid.footer.onClick('first');\n"+
571                                             "   }); \n"+
572                                             "}\n"
573                                     },
574                                     "|xns": "Roo.Toolbar"
575                                 },
576                                 {
577                                     "text": "Edit",
578                                     "xtype": "Button",
579                                     "cls": "x-btn-text-icon",
580                                     "|icon": "Roo.rootURL + 'images/default/tree/leaf.gif'",
581                                     "listeners": {
582                                         "|click": "function()\n"+
583                                             "{\n"+
584                                             "    var s = _this.grid.getSelectionModel().getSelections();\n"+
585                                             "    if (!s.length || (s.length > 1))  {\n"+
586                                             "        Roo.MessageBox.alert(\"Error\", s.length ? \"Select only one Row\" : \"Select a Row\");\n"+
587                                             "        return;\n"+
588                                             "    }\n"+
589                                             "    if (!_this.dialog) return;\n" +
590                                             "    _this.dialog.show(s[0].data, function() {\n"+
591                                             "        _this.grid.footer.onClick('first');\n"+
592                                             "    }); \n"+
593                                             "    \n"+
594                                             "}\n" 
595                                         
596                                     },
597                                     "|xns": "Roo.Toolbar"
598                                 },
599                                 {
600                                     "text": "Delete",
601                                     "cls": "x-btn-text-icon",
602                                     "|icon": "rootURL + '/Pman/templates/images/trash.gif'",
603                                     "xtype": "Button",
604                                     "listeners": {
605                                         "|click": "function()\n"+
606                                             "{\n"+
607                                             "     Pman.genericDelete(_this, '" + reader.table + "'); \n"+
608                                             "}\n"+
609                                             "        "
610                                     },
611                                     "|xns": "Roo.Toolbar"
612                                 }
613                             ]
614                         }, // end toolbar
615                     ].concat( reader.colmodel)
616                 }
617             ]
618             
619             
620         }, null, 4)
621     )
622     
623     /// FORMS..
624     
625     dir = GLib.get_home_dir() + '/.Builder/Roo.form.Form'; 
626     if (!File.isDirectory(dir)) {
627         File.mkdir(dir);
628     }
629     var formElements = [];
630     var formHeight = 50;
631     for (var k in reader.form) {
632         if (k == 'id') { // should really do primary key testing..
633             continue;
634         }
635         formHeight += reader.form[k].xtype == 'TextArea' ? 100 : 30;
636         formElements.push(reader.form[k]);
637     }
638     formElements.push(reader.form['id']);
639
640     print("WRITE: " +  dir + '/' + cfg.DBNAME + '_' + reader.table + '.json');
641     var frmCfg = 
642     {
643         '|xns' : 'Roo.form',
644         xtype : "Form",
645         listeners : {
646             "|actioncomplete" : "function(_self,action)\n"+
647                 "{\n"+
648                 "    if (action.type == 'setdata') {\n"+
649                 "       //_this.dialog.el.mask(\"Loading\");\n"+
650                 "       //this.load({ method: 'GET', params: { '_id' : _this.data.id }});\n"+
651                 "       return;\n"+
652                 "    }\n"+
653                 "    if (action.type == 'load') {\n"+
654                 "        _this.dialog.el.unmask();\n"+
655                 "        return;\n"+
656                 "    }\n"+
657                 "    if (action.type =='submit') {\n"+
658                 "    \n"+
659                 "        _this.dialog.el.unmask();\n"+
660                 "        _this.dialog.hide();\n"+
661                 "    \n"+
662                 "         if (_this.callback) {\n"+
663                 "            _this.callback.call(_this, _this.form.getValues());\n"+
664                 "         }\n"+
665                 "         _this.form.reset();\n"+
666                 "         return;\n"+
667                 "    }\n"+
668                 "}\n",
669             
670             "|rendered" : "function (form)\n"+
671                 "{\n"+
672                 "    _this.form= form;\n"+
673                 "}\n"
674         },
675         method : "POST",
676         style : "margin:10px;",
677         "|url" : "baseURL + '/Roo/" + reader.table + ".php'",
678         items : formElements
679     };
680     
681     
682     File.write(
683         dir + '/' + cfg.DBNAME + '_' + reader.table + '.json',
684             
685        
686         JSON.stringify( frmCfg, null, 4)
687     );
688             
689             
690    
691    
692    
693      /// COMBO..
694     
695     dir = GLib.get_home_dir() + '/.Builder/Roo.form.ComboBox'; 
696     if (!File.isDirectory(dir)) {
697         File.mkdir(dir);
698     }
699    
700     print("WRITE: " +  dir + '/' + cfg.DBNAME + '_' + reader.table + '.json');
701     
702     File.write(
703         dir + '/' + cfg.DBNAME + '_' + reader.table + '.json',
704             
705        
706         JSON.stringify(reader.combo, null, 4)
707     );
708             
709    
710    
711    
712    
713    
714     // DIALOG.
715    
716    
717     dir = GLib.get_home_dir() + '/.Builder/Roo.LayoutDialog'; 
718     if (!File.isDirectory(dir)) {
719         File.mkdir(dir);
720     }
721     var formElements = [];
722     for (var k in reader.form) {
723         if (k == 'id') { // should really do primary key testing..
724             continue;
725         }
726         formElements.push(reader.form[k]);
727     }
728     formElements.push(reader.form['id']);
729
730     print("WRITE: " +  dir + '/' + cfg.DBNAME + '_' + reader.table + '.json');
731     
732     File.write(
733         dir + '/' + cfg.DBNAME + '_' + reader.table + '.json',
734             
735        
736         JSON.stringify({
737        
738             "closable": false,
739             "collapsible": false,
740             "height": formHeight,
741             "resizable": false,
742             "title": "Edit / Create " + reader.table,
743             "width": 400,
744             "xtype": "LayoutDialog",
745             "|xns": "Roo",
746             "items": [
747                 {
748                     "|xns": "Roo",
749                     "xtype": "LayoutRegion",
750                     "*prop": "center"
751                 },
752                 {
753                     "region": "center",
754                     "xtype": "ContentPanel",
755                     "|xns": "Roo",
756                     "items": [
757                         frmCfg
758                     ]
759                 },
760                 
761                 {
762                     "listeners": {
763                         "click": "function (_self, e)\n{\n    _this.dialog.hide();\n}"
764                     },
765                     "*prop": "buttons[]",
766                     "text": "Cancel",
767                     "xtype": "Button",
768                     "|xns": "Roo"
769                 },
770                 {
771                     "listeners": {
772                         "click": "function (_self, e)\n{\n    // do some checks?\n     \n    \n    _this.dialog.el.mask(\"Saving\");\n    _this.form.doAction(\"submit\");\n\n}"
773                     },
774                     "*prop": "buttons[]",
775                     "text": "Save",
776                     "xtype": "Button",
777                     "|xns": "Roo"
778                 }
779             ]
780         }, null,4)
781     );
782    
783    
784    
785 });
786
787