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