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