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  * 
16  */
17 Gda  = imports.gi.Gda;
18 GObject = imports.gi.GObject;
19
20 GLib = imports.gi.GLib;
21
22 console = imports['../../../console.js'];
23 File = imports['../../../File.js'].File;
24 Gda.init();
25
26 var prov = Gda.Config.list_providers ();
27 //print(prov.dump_as_string());
28 var args = Array.prototype.slice.call(Seed.argv);
29 args.shift();args.shift();// remove first 2
30 if (args.length < 1) {
31     var sample = {
32         DB_NAME : "XXX",
33         USERNAME : "YYY",
34         PASSWORD: "ZZZ",
35         INI : "/path/to/mydb.ini",
36     }
37     print("Usage : seed generate.js  '" + JSON.stringify(sample) +"'");
38     Seed.quit();
39 }
40 var cfg = JSON.parse(args[0]);
41
42 var   cnc = Gda.Connection.open_from_string ("MySQL", "DB_NAME=" + cfg.DB_NAME, 
43                                               "USERNAME=" + cfg.USERNAME + ';PASSWORD=' + cfg.PASSWORD,
44                                               Gda.ConnectionOptions.NONE, null);
45
46
47
48                                               
49
50  
51 Gda.DataSelect.prototype.fetchAll = function()
52 {
53     var cols = [];
54     
55     for (var i =0;i < this.get_n_columns(); i++) {
56         cols.push(this.get_column_name(i));
57     }
58     //console.dump(cols);
59     var iter = this.create_iter();
60     var res = [];
61     while (iter.move_next()) {
62         if (cols.length == 1) {
63             res.push(iter.get_value_at(0).get_string());
64             continue;
65         }
66         var add = { };
67         
68         cols.forEach(function(n,i) {
69            var val = iter.get_value_at(i);
70            var type = GObject.type_name(val.g_type) ;
71            var vs = type == 'GdaBlob' ? val.value.to_string(1024) : val.value;
72          //  print(n + " : TYPE: " + GObject.type_name(val.g_type) + " : " + vs);
73             //print (n + '=' + iter.get_value_at(i).value);
74             add[n] = vs;
75         });
76         
77         res.push(add);
78         
79     }
80     return res;
81
82 }
83
84 var map = {
85     'date' : 'date',
86     'datetime' : 'string',
87     'int' : 'int',
88     'bigint' : 'int',
89     'char' : 'int',
90     'tinyint' : 'int',
91     'decimal' : 'float',
92     'float' : 'float',
93     'varchar' : 'string',
94     'text' : 'string',
95     'longtext' : 'string',
96     'mediumtext' : 'string',
97     'enum' : 'string',
98     
99     
100 }
101
102 var ini = { }
103
104 function readIni(fn)
105 {
106     var key_file = GLib.key_file_new();
107     if (!GLib.key_file_load_from_file (key_file, fn , GLib.KeyFileFlags.NONE )) {
108         return;
109     }
110    
111     var groups = GLib.key_file_get_groups(key_file);
112     groups.forEach(function(g) {
113         ini[g] = {}
114            
115         var keys = GLib.key_file_get_keys(key_file,g);
116         keys.forEach(function(k) {
117             ini[g][k] = GLib.key_file_get_value(key_file,g,k);
118         })
119     })
120     
121 }
122 if (File.isFile(cfg.INI)) {
123     if (cfg.INI.match(/links\.ini$/)) {
124         readIni(cfg.INI);
125     } else {
126         readIni(cfg.INI.replace(/\.ini$/, ".links.ini"));
127     }
128 }
129
130 if (File.isDirectory(cfg.INI)) {
131         
132
133     //--- load ini files..
134     // this is very specific.
135     var dirs = File.list( GLib.get_home_dir() + '/gitlive').filter( 
136         function(e) { return e.match(/^Pman/); }
137     );
138     
139     dirs.forEach(function(d) {
140         // this currently misses the web.*/Pman/XXXX/DataObjects..
141         var path = GLib.get_home_dir() + '/gitlive/' + d + '/DataObjects';
142         if (!File.isDirectory(path)) {
143             path = GLib.get_home_dir() + '/gitlive/' + d + '/Pman/DataObjects';
144         }
145         if (!File.isDirectory(path)) {
146             return; //skip
147         }
148         var inis = File.list(path).filter(
149             function(e) { return e.match(/\.links\.ini$/); }
150         );
151         if (!inis.length) {
152             return;
153         }
154         
155         inis.forEach(function(i) {
156             readIni(path + '/' + i); 
157             
158         })
159
160         
161         
162     });
163 }
164  //console.dump(ini);
165
166
167  //Seed.quit();
168
169 //GLib.key_file_load_from_file (key_file, String file, KeyFileFlags flags) : Boolean
170
171
172
173
174
175
176
177
178
179
180
181 var tables = Gda.execute_select_command(cnc, "SHOW TABLES").fetchAll();
182 var readers = [];
183 tables.forEach(function(table) {
184     //print(table);
185     var schema = Gda.execute_select_command(cnc, "DESCRIBE `" + table+'`').fetchAll();
186     var reader = []; 
187     var colmodel = []; 
188     var firstTxtCol = '';
189     schema.forEach(function(e)  {
190         var type = e.Type.match(/([^(]+)\(([^\)]+)\)/);
191         var row  = { }; 
192         if (type) {
193             e.Type = type[1];
194             e.Size = type[2];
195         }
196         
197         
198         
199         row.name = e.Field;
200         
201         
202         if (typeof(map[e.Type]) == 'undefined') {
203            console.dump(e);
204            throw {
205                 name: "ArgumentError", 
206                 message: "Unknown mapping for type : " + e.Type
207             };
208         }
209         row.type = map[e.Type];
210         
211         if (row.type == 'string' && !firstTxtCol.length) {
212             firstTxtCol = row.name;
213         }
214         
215         if (row.type == 'date') {
216             row.dateFormat = 'Y-m-d';
217         }
218         reader.push(row);
219         colmodel.push({
220             "xtype": "ColumnModel",
221             "header": row.name,
222             "width": 100,
223             "dataIndex": row.name,
224             "|renderer": row.type != 'date ' ? 
225                     "function(v) { return String.format('{0}', v); }" :
226                     "function(v) { return String.format('{0}', v ? v.format('d/M/Y') : ''); }" , // special for date
227             "|xns": "Roo.grid",
228             "*prop": "colModel[]"
229         })
230     });
231     
232     
233     
234     
235     //print(JSON.stringify(reader,null,4));
236     readers.push({
237         table : table ,
238         reader :  reader,
239         oreader : JSON.parse(JSON.stringify(reader)), // dupe it..
240         colmodel : colmodel,
241         firstTxtCol : firstTxtCol
242     });
243     
244     //console.dump(schema );
245     
246      
247 });
248
249
250
251 // merge in the linked tables..
252 readers.forEach(function(reader) {
253     if (typeof(ini[reader.table]) == 'undefined') {
254      
255         return;
256     }
257    print("OVERLAY - " + reader.table);
258     // we have a map..
259     for (var col in ini[reader.table]) {
260         var kv = ini[reader.table][col].split(':');
261         var add = readers.filter(function(r) { return r.table == kv[0] })[0];
262         add.oreader.forEach(function(or) {
263             reader.reader.push({
264                 name : col + '_' + or.name,
265                 type : or.type
266             });
267         });
268              
269     };
270     
271     
272 });
273
274 readers.forEach(function(reader) {
275     delete reader.oreader;
276 });
277
278  
279
280
281
282 //print(JSON.stringify(readers, null, 4));
283
284 readers.forEach(function(reader) {
285     
286
287     var dir = GLib.get_home_dir() + '/.Builder/Roo.data.JsonReader'; 
288     if (!File.isDirectory(dir)) {
289         File.mkdir(dir);
290     }
291     print("WRITE: " +  dir + '/' + cfg.DB_NAME + '_' + reader.table + '.json');
292     
293                 
294     var jreader = {
295         '|xns' : 'Roo.data',
296         xtype : "JsonReader",
297         totalProperty : "total",
298         root : "data",
299         '*prop' : "reader",
300         id : 'id', // maybe no..
301         '|fields' :  JSON.stringify(reader.reader, null,4)
302     };
303     
304     File.write(
305         dir + '/' + cfg.DB_NAME + '_' + reader.table + '.json',
306         JSON.stringify(jreader, null, 4)
307     )
308     
309     dir = GLib.get_home_dir() + '/.Builder/Roo.GridPanel'; 
310     if (!File.isDirectory(dir)) {
311         File.mkdir(dir);
312     }
313     print("WRITE: " +  dir + '/' + cfg.DB_NAME + '_' + reader.table + '.json');
314     
315       File.write(
316         dir + '/' + cfg.DB_NAME + '_' + reader.table + '.json',
317             
318        
319         JSON.stringify({
320             '|xns' : 'Roo',
321             xtype : "GridPanel",
322             "title": reader.table,
323             "fitToframe": true,
324             "fitContainer": true,
325             "tableName": reader.table,
326             "background": true,
327             "listeners": {
328                 "|activate": "function() {\n    _this.panel = this;\n    if (_this.grid) {\n        _this.grid.footer.onClick('first');\n    }\n}"
329             },
330             "items": [
331                 {
332                     "*prop": "grid",
333                     "xtype": "Grid",
334                     "autoExpandColumn": reader.firstTxtCol,
335                     "loadMask": true,
336                     "listeners": {
337                         "|render": "function() \n" +
338                             "{\n" +
339                             "   _this.grid = this; \n" +
340                             "    //_this.dialog = Pman.Dialog.FILL_IN\n" +
341                             "    if (_this.panel.active) {\n" +
342                             "       this.footer.onClick('first');\n" +
343                             "    }\n" +
344                             "}"
345                     },
346                     "|xns": "Roo.grid",
347
348                     "items": [
349                         {
350                             "*prop": "dataSource",
351                             "xtype": "Store",
352                             
353                             "|xns": "Roo.data",
354                             "items": [
355                                 
356                                 {
357                                     "*prop": "proxy",
358                                     "xtype": "HttpProxy",
359                                     "method": "GET",
360                                     "|url": "baseURL + '/Roo/" + reader.table + ".php'",
361                                     "|xns": "Roo.data"
362                                 },
363                                 jreader
364                             ]
365                         },
366                         {
367                             "*prop": "footer",
368                             "xtype": "PagingToolbar",
369                             "pageSize": 25,
370                             "displayInfo": true,
371                             "displayMsg": "Displaying " + reader.table + "{0} - {1} of {2}",
372                             "emptyMsg": "No " + reader.table + " found",
373                             "|xns": "Roo"
374                         },
375                         {
376                             "*prop": "toolbar",
377                             "xtype": "Toolbar",
378                             "|xns": "Roo",
379                             "items": [
380                                 {
381                                     "text": "Add",
382                                     "xtype": "Button",
383                                     "cls": "x-btn-text-icon",
384                                     "|icon": "Roo.rootURL + 'images/default/dd/drop-add.gif'",
385                                     "listeners": {
386                                         "|click": "function()\n"+
387                                             "{\n"+
388                                             "   //yourdialog.show( { id : 0 } , function() {\n"+
389                                             "   //  _this.grid.footer.onClick('first');\n"+
390                                             "   //}); \n"+
391                                             "}\n"
392                                     },
393                                     "|xns": "Roo"
394                                 },
395                                 {
396                                     "text": "Edit",
397                                     "xtype": "Button",
398                                     "cls": "x-btn-text-icon",
399                                     "|icon": "Roo.rootURL + 'images/default/tree/leaf.gif'",
400                                     "listeners": {
401                                         "|click": "function()\n"+
402                                             "{\n"+
403                                             "    var s = _this.grid.getSelectionModel().getSelections();\n"+
404                                             "    if (!s.length || (s.length > 1))  {\n"+
405                                             "        Roo.MessageBox.alert(\"Error\", s.length ? \"Select only one Row\" : \"Select a Row\");\n"+
406                                             "        return;\n"+
407                                             "    }\n"+
408                                             "    \n"+
409                                             "    //_this.dialog.show(s[0].data, function() {\n"+
410                                             "    //    _this.grid.footer.onClick('first');\n"+
411                                             "    //   }); \n"+
412                                             "    \n"+
413                                             "}\n" 
414                                         
415                                     },
416                                     "|xns": "Roo"
417                                 },
418                                 {
419                                     "text": "Delete",
420                                     "cls": "x-btn-text-icon",
421                                     "|icon": "rootURL + '/Pman/templates/images/trash.gif'",
422                                     "xtype": "Button",
423                                     "listeners": {
424                                         "|click": "function()\n"+
425                                             "{\n"+
426                                             "   //Pman.genericDelete(_this, _this.grid.tableName); \n"+
427                                             "}\n"+
428                                             "        "
429                                     },
430                                     "|xns": "Roo"
431                                 }
432                             ]
433                         }, // end toolbar
434                     ].concat( reader.colmodel)
435                 }
436             ]
437             
438             
439         }, null, 4)
440     )
441     
442     
443     
444     
445     
446
447 });
448
449
450
451
452