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