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