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