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