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