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 print(JSON.stringify(ini, null,4));
165  //console.dump(ini);
166
167
168  //Seed.quit();
169
170 //GLib.key_file_load_from_file (key_file, String file, KeyFileFlags flags) : Boolean
171
172
173
174  
175
176 var tables = Gda.execute_select_command(cnc, "SHOW TABLES").fetchAll();
177 var readers = [];
178 tables.forEach(function(table) {
179     //print(table);
180     var schema = Gda.execute_select_command(cnc, "DESCRIBE `" + table+'`').fetchAll();
181     var reader = []; 
182     var colmodel = []; 
183     var firstTxtCol = '';
184     schema.forEach(function(e)  {
185         var type = e.Type.match(/([^(]+)\(([^\)]+)\)/);
186         var row  = { }; 
187         if (type) {
188             e.Type = type[1];
189             e.Size = type[2];
190         }
191         
192         
193         
194         row.name = e.Field;
195         
196         
197         if (typeof(map[e.Type]) == 'undefined') {
198            console.dump(e);
199            throw {
200                 name: "ArgumentError", 
201                 message: "Unknown mapping for type : " + e.Type
202             };
203         }
204         row.type = map[e.Type];
205         
206         if (row.type == 'string' && !firstTxtCol.length) {
207             firstTxtCol = row.name;
208         }
209         
210         if (row.type == 'date') {
211             row.dateFormat = 'Y-m-d';
212         }
213         reader.push(row);
214         
215         colmodel.push({
216             "xtype": "ColumnModel",
217             "header": row.name,
218             "width":  row.type == 'string' ? 200 : 75,
219             "dataIndex": row.name,
220             "|renderer": row.type != 'date' ? 
221                     "function(v) { return String.format('{0}', v); }" :
222                     "function(v) { return String.format('{0}', v ? v.format('d/M/Y') : ''); }" , // special for date
223             "|xns": "Roo.grid",
224             "*prop": "colModel[]"
225         })
226     });
227     
228     
229     
230     
231     //print(JSON.stringify(reader,null,4));
232     readers.push({
233         table : table ,
234         reader :  reader,
235         oreader : JSON.parse(JSON.stringify(reader)), // dupe it..
236         colmodel : colmodel,
237         firstTxtCol : firstTxtCol
238     });
239     
240     //console.dump(schema );
241     
242      
243 });
244
245
246
247 // merge in the linked tables..
248 readers.forEach(function(reader) {
249     if (typeof(ini[reader.table]) == 'undefined') {
250      
251         return;
252     }
253    print("OVERLAY - " + reader.table);
254     // we have a map..
255     for (var col in ini[reader.table]) {
256         var kv = ini[reader.table][col].split(':');
257         var add = readers.filter(function(r) { return r.table == kv[0] })[0];
258         add.oreader.forEach(function(or) {
259             reader.reader.push({
260                 name : col + '_' + or.name,
261                 type : or.type
262             });
263         });
264              
265     };
266     
267     
268 });
269
270 readers.forEach(function(reader) {
271     delete reader.oreader;
272 });
273
274  
275
276
277
278 //print(JSON.stringify(readers, null, 4));
279
280 readers.forEach(function(reader) {
281     
282
283     var dir = GLib.get_home_dir() + '/.Builder/Roo.data.JsonReader'; 
284     if (!File.isDirectory(dir)) {
285         File.mkdir(dir);
286     }
287     
288     // READERS
289     print("WRITE: " +  dir + '/' + cfg.DB_NAME + '_' + reader.table + '.json');
290     
291                 
292     var jreader = {
293         '|xns' : 'Roo.data',
294         xtype : "JsonReader",
295         totalProperty : "total",
296         root : "data",
297         '*prop' : "reader",
298         id : 'id', // maybe no..
299         '|fields' :  JSON.stringify(reader.reader, null,4)
300     };
301     
302     File.write(
303         dir + '/' + cfg.DB_NAME + '_' + reader.table + '.json',
304         JSON.stringify(jreader, null, 4)
305     )
306     
307     
308     // GRIDS
309     dir = GLib.get_home_dir() + '/.Builder/Roo.GridPanel'; 
310     if (!File.isDirectory(dir)) {
311         File.mkdir(dir);
312     }
313     
314
315     print("WRITE: " +  dir + '/' + cfg.DB_NAME + '_' + reader.table + '.json');
316     
317     File.write(
318         dir + '/' + cfg.DB_NAME + '_' + reader.table + '.json',
319             
320        
321         JSON.stringify({
322             '|xns' : 'Roo',
323             xtype : "GridPanel",
324             "title": reader.table,
325             "fitToframe": true,
326             "fitContainer": true,
327             "tableName": reader.table,
328             "background": true,
329             "listeners": {
330                 "|activate": "function() {\n    _this.panel = this;\n    if (_this.grid) {\n        _this.grid.footer.onClick('first');\n    }\n}"
331             },
332             "items": [
333                 {
334                     "*prop": "grid",
335                     "xtype": "Grid",
336                     "autoExpandColumn": reader.firstTxtCol,
337                     "loadMask": true,
338                     "listeners": {
339                         "|render": "function() \n" +
340                             "{\n" +
341                             "   _this.grid = this; \n" +
342                             "    //_this.dialog = Pman.Dialog.FILL_IN\n" +
343                             "    if (_this.panel.active) {\n" +
344                             "       this.footer.onClick('first');\n" +
345                             "    }\n" +
346                             "}"
347                     },
348                     "|xns": "Roo.grid",
349
350                     "items": [
351                         {
352                             "*prop": "dataSource",
353                             "xtype": "Store",
354                             
355                             "|xns": "Roo.data",
356                             "items": [
357                                 
358                                 {
359                                     "*prop": "proxy",
360                                     "xtype": "HttpProxy",
361                                     "method": "GET",
362                                     "|url": "baseURL + '/Roo/" + reader.table + ".php'",
363                                     "|xns": "Roo.data"
364                                 },
365                                 jreader
366                             ]
367                         },
368                         {
369                             "*prop": "footer",
370                             "xtype": "PagingToolbar",
371                             "pageSize": 25,
372                             "displayInfo": true,
373                             "displayMsg": "Displaying " + reader.table + "{0} - {1} of {2}",
374                             "emptyMsg": "No " + reader.table + " found",
375                             "|xns": "Roo"
376                         },
377                         {
378                             "*prop": "toolbar",
379                             "xtype": "Toolbar",
380                             "|xns": "Roo",
381                             "items": [
382                                 {
383                                     "text": "Add",
384                                     "xtype": "Button",
385                                     "cls": "x-btn-text-icon",
386                                     "|icon": "Roo.rootURL + 'images/default/dd/drop-add.gif'",
387                                     "listeners": {
388                                         "|click": "function()\n"+
389                                             "{\n"+
390                                             "   //yourdialog.show( { id : 0 } , function() {\n"+
391                                             "   //  _this.grid.footer.onClick('first');\n"+
392                                             "   //}); \n"+
393                                             "}\n"
394                                     },
395                                     "|xns": "Roo"
396                                 },
397                                 {
398                                     "text": "Edit",
399                                     "xtype": "Button",
400                                     "cls": "x-btn-text-icon",
401                                     "|icon": "Roo.rootURL + 'images/default/tree/leaf.gif'",
402                                     "listeners": {
403                                         "|click": "function()\n"+
404                                             "{\n"+
405                                             "    var s = _this.grid.getSelectionModel().getSelections();\n"+
406                                             "    if (!s.length || (s.length > 1))  {\n"+
407                                             "        Roo.MessageBox.alert(\"Error\", s.length ? \"Select only one Row\" : \"Select a Row\");\n"+
408                                             "        return;\n"+
409                                             "    }\n"+
410                                             "    \n"+
411                                             "    //_this.dialog.show(s[0].data, function() {\n"+
412                                             "    //    _this.grid.footer.onClick('first');\n"+
413                                             "    //   }); \n"+
414                                             "    \n"+
415                                             "}\n" 
416                                         
417                                     },
418                                     "|xns": "Roo"
419                                 },
420                                 {
421                                     "text": "Delete",
422                                     "cls": "x-btn-text-icon",
423                                     "|icon": "rootURL + '/Pman/templates/images/trash.gif'",
424                                     "xtype": "Button",
425                                     "listeners": {
426                                         "|click": "function()\n"+
427                                             "{\n"+
428                                             "   //Pman.genericDelete(_this, _this.grid.tableName); \n"+
429                                             "}\n"+
430                                             "        "
431                                     },
432                                     "|xns": "Roo"
433                                 }
434                             ]
435                         }, // end toolbar
436                     ].concat( reader.colmodel)
437                 }
438             ]
439             
440             
441         }, null, 4)
442     )
443     
444     /// FORMS..
445     
446     dir = GLib.get_home_dir() + '/.Builder/Roo.form.Form'; 
447     if (!File.isDirectory(dir)) {
448         File.mkdir(dir);
449     }
450     
451
452     print("WRITE: " +  dir + '/' + cfg.DB_NAME + '_' + reader.table + '.json');
453     
454     File.write(
455         dir + '/' + cfg.DB_NAME + '_' + reader.table + '.json',
456             
457        
458         JSON.stringify({
459             '|xns' : 'Roo.form',
460             xtype : "Form",
461             
462             
463     
464     
465
466 });
467
468
469
470
471