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