dbgenerate.js
[app.Builder.js] / dbgenerate.js
1 //<script type="text/javascript">
2
3 /**
4  * This is a hacky generator to generate element definitions for the Roo version from the database
5  * 
6  * Let's see if libgda can be used to generate our Readers for roo...
7  * 
8  * Concept - conect to database..
9  * 
10  * list tables
11  * 
12  * extra schemas..
13  * 
14  * write readers..
15  * 
16  * usage: seed generate.js
17  *
18  *
19  *
20  *
21  *Hack needed to latest GLib-2.0.gir 
22  *
23  * <record name="KeyFile" c:type="GKeyFile" disguised="1">
24         <constructor name="new" c:identifier="g_key_file_new">
25         <return-value transfer-ownership="full">
26           <type name="KeyFile" c:type="GKeyFile*"/>
27         </return-value>
28       </constructor>
29  *
30  *
31  * remove introspectable =0 from g_key_file_get_groups
32  *   and add transfer-owneership = none to return value
33  * remove introspectable =0 from g_key_file_get_keys
34  *   and add transfer-owneership = none to return value* 
35  * 
36  */
37 Gda  = imports.gi.Gda;
38 GObject = imports.gi.GObject;
39
40 GLib = imports.gi.GLib;
41
42 console = imports.console;
43 File = imports.File.File;
44 Options = imports.Options.Options;
45
46 //Gda.init();
47
48 var prov = Gda.Config.list_providers ();
49 //print(prov.dump_as_string());
50
51 var o = new Options({
52     help_description : 'Element builder for App Builder based on database schema',
53     
54     options:  [
55         { arg_long : 'DBTYPE' , arg_short : 't', description : 'Database Type (eg. MySQL or PostgreSQL ' },
56         { arg_long : 'DBNAME' , arg_short : 'd', description : 'Database Name' },
57         { arg_long : 'USERNAME' , arg_short : 'u', description : 'Username'},
58         { arg_long : 'PASSWORD' , arg_short : 'p', description : 'Password' , arg_default :'' },
59         { arg_long : 'INI' , arg_short : 'I', description :
60                     'Either base directory which has Pman/***/DataObjects/***.links.ini or location of ini file.' },
61     ]
62            
63 })
64
65
66
67 var cfg = o.parse(Seed.argv);
68 print(JSON.stringify(cfg, null,4));
69
70 var   cnc = Gda.Connection.open_from_string (cfg.DBTYPE,
71          "DB_NAME=" + cfg.DBNAME, 
72         "USERNAME=" + cfg.USERNAME + ';PASSWORD=' + cfg.PASSWORD,
73         Gda.ConnectionOptions.NONE, null);
74
75
76
77                                               
78
79  
80 Gda.DataSelect.prototype.fetchAll = function()
81 {
82     var cols = [];
83     
84     for (var i =0;i < this.get_n_columns(); i++) {
85         cols.push(this.get_column_name(i));
86     }
87     //print(JSON.stringify(cols, null,4));
88     var iter = this.create_iter();
89     var res = [];
90     //print(this.get_n_rows());
91     var _this = this;
92     for (var r = 0; r < this.get_n_rows(); r++) {
93         
94         // single clo..
95         //print("GOT ROW");
96         if (cols.length == 1) {
97             res.push(this.get_value_at(0,r).get_string());
98             continue;
99         }
100         var add = { };
101         
102         cols.forEach(function(n,i) {
103             var val = _this.get_value_at(i,r);
104             var type = GObject.type_name(val.g_type) ;
105             var vs = ['GdaBinary', 'GdaBlob' ].indexOf(type) > -1 ? val.value.to_string(1024) : val.value;
106             //print(n + " : TYPE: " + GObject.type_name(val.g_type) + " : " + vs);
107             //print (n + '=' + iter.get_value_at(i).value);
108             add[n] = vs;
109         });
110         
111         res.push(add);
112         
113     }
114     return res;
115
116 }
117
118 var map = {
119     'date' : 'date',
120     'datetime' : 'date',
121     'timestamp with time zone' : 'date',
122     'timestamp without time zone' : 'date',
123     'time' : 'string', //bogus
124     'int' : 'int',
125     'integer' : 'int',
126     'bigint' : 'int',
127     'double' : 'float',
128     'tinyint' : 'int',
129     'smallint' : 'int',
130     'decimal' : 'float',
131     'float' : 'float',
132     'numeric' : 'float',
133     'char' : 'string',
134     'character' : 'string',
135     'character varying' : 'string',
136     'varchar' : 'string',
137     'text' : 'string',
138     'longtext' : 'string',
139     'tinytext' : 'string',
140     'mediumtext' : 'string',
141     'enum' : 'string',
142     'timestamp' : 'number',
143     'blob' : 'text',
144     'bytea' : 'text',
145     'boolean' : 'int',
146     'text[]' : 'string',
147     
148 }
149
150 var ini = { }
151
152 function readIni(fn)
153 {
154     print('Read INI : ' + fn);
155     var key_file = new GLib.KeyFile.c_new();
156     if (!key_file.load_from_file (fn , GLib.KeyFileFlags.NONE )) {
157         return;
158     }
159    
160     var groups = key_file.get_groups();
161     groups.forEach(function(g) {
162         print("KEY:"+g);
163         ini[g] = {}
164         
165         var keys = key_file.get_keys(g);
166         if (!keys) { return; }
167         
168         keys.forEach(function(k) {
169                 print("GET val: " + k);
170                 ini[g][k] = key_file.get_value(g,k);
171                 print(ini[g][k] );
172         });
173         print("DONE KEY:"+g);
174     });
175     print("DONE KEYS");
176 }
177  
178 if (File.isFile(cfg.INI)) {
179     if (cfg.INI.match(/links\.ini$/)) {
180         readIni(cfg.INI);
181     } else {
182         readIni(cfg.INI.replace(/\.ini$/, ".links.ini"));
183     }
184 }
185
186
187 if (File.isDirectory(cfg.INI)) {
188         
189
190     //--- load ini files..
191     // this is very specific.
192     
193     var dirs = File.list( cfg.INI + '/Pman').filter( 
194         function(e) { 
195             if (!File.isDirectory(cfg.INI + '/Pman/' + e + '/DataObjects')) {
196                 return false;
197             }
198             return true;
199         }
200     );
201     
202      
203     dirs.forEach(function(d) {
204         // this currently misses the web.*/Pman/XXXX/DataObjects..
205         var path = cfg.INI + '/Pman/' + d + '/DataObjects';
206          
207         if (!File.isDirectory(path)) {
208             return; //skip
209         }
210         var inis = File.list(path).filter(
211             function(e) { return e.match(/\.links\.ini$/); }
212         );
213         if (!inis.length) {
214             return;
215         }
216         
217         inis.forEach(function(i) {
218             readIni(path + '/' + i); 
219             
220         })
221  
222     });
223     // look at web.XXXX/Pman/XXX/DataObjects/*.ini
224     var inis = File.list(cfg.INI).filter(
225         function(e) { return e.match(/\.links\.ini$/); }
226     )
227     
228      inis.forEach(function(i) {
229         readIni(path + '/' + i); 
230         
231     })
232     
233     
234 }
235 //print(JSON.stringify(ini, null,4));
236  //console.dump(ini);
237
238
239  //Seed.quit();
240
241 //GLib.key_file_load_from_file (key_file, String file, KeyFileFlags flags) : Boolean
242
243
244 switch(cfg.DBTYPE) {
245     case "MySQL":
246         query_tables = "SHOW TABLES";
247         query_describe_table = "DESCRIBE `%s`";
248         break;
249     
250     case 'PostgreSQL':
251         query_tables = "select c.relname FROM pg_catalog.pg_class c " + 
252             "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace " + 
253             "WHERE c.relkind IN ('r','') AND n.nspname NOT IN ('pg_catalog', 'pg_toast')" +
254             "AND pg_catalog.pg_table_is_visible(c.oid) ";
255          query_describe_table =  
256                 "SELECT " +
257                 "f.attnum AS number, " +
258                 "f.attname AS Field, " +
259                 "f.attnum, " +
260                 "CASE WHEN f.attnotnull = 't' THEN 'NO' ELSE 'YES' END AS isNull, " + 
261                 "pg_catalog.format_type(f.atttypid,f.atttypmod) AS Type, " +
262                 "CASE WHEN p.contype = 'p' THEN 't' ELSE 'f' END AS primarykey, " +
263                 "CASE WHEN p.contype = 'u' THEN 't' ELSE 'f' END AS uniquekey, " +
264                 "CASE WHEN p.contype = 'f' THEN g.relname END AS foreignkey, " +
265                 "CASE WHEN p.contype = 'f' THEN p.confkey END AS foreignkey_fieldnum, " +
266                 "CASE WHEN p.contype = 'f' THEN g.relname END AS foreignkey, " +
267                 "CASE WHEN p.contype = 'f' THEN p.conkey END AS foreignkey_connnum, " +
268                 "CASE WHEN f.atthasdef = 't' THEN d.adsrc END AS default " +
269                 "FROM pg_attribute f JOIN pg_class c ON c.oid = f.attrelid " +
270                 "        JOIN pg_type t ON t.oid = f.atttypid " +
271                 "        LEFT JOIN pg_attrdef d ON d.adrelid = c.oid AND d.adnum = f.attnum " +
272                 "        LEFT JOIN pg_namespace n ON n.oid = c.relnamespace " +
273                 "        LEFT JOIN pg_constraint p ON p.conrelid = c.oid AND f.attnum = ANY ( p.conkey ) " +
274                 "        LEFT JOIN pg_class AS g ON p.confrelid = g.oid " +
275                 "WHERE c.relkind = 'r'::char AND n.nspname = '%n' " +
276                 "AND c.relname = '%s' AND f.attnum > 0 ORDER BY number";
277                 
278                 
279                 
280         break;
281     default:
282         throw "Invalid data base type " + cfg.DBTYPE + " should be MySQL or PostgreSQL";
283 /*
284            "Field": "province",
285         "Type": "varchar(255)",
286         "Null": "NO", << or is null
287         "Key": null,
288         "Default": null,
289         "Extra": 
290 */  
291 }
292
293
294  
295
296 var tables = cnc.execute_select_command( query_tables).fetchAll();
297 print(JSON.stringify(tables));
298
299 var readers = [];
300 tables.forEach(function(table) {
301     //print(table);
302     var schema = cnc.execute_select_command(
303             query_describe_table.replace(/%s/, table).replace(/%n/,'public')
304             ).fetchAll();
305     
306     
307     var reader = []; 
308     var colmodel = []; 
309     var combofields= [ { name : 'id', type: 'int' } ]; // technically the primary key..
310          
311     var form = {}
312        
313     var firstTxtCol = '';
314     
315     //print(JSON.stringify(schema, null,4));    Seed.quit();
316     
317     schema.forEach(function(e)  {
318         e.Type = e.Type || e.type;
319         e.Field = e.Field || e.field;
320          
321         var type = e.Type.match(/([^(]+)\(([^\)]+)\)/);
322         var row  = { }; 
323         if (type) {
324             e.Type = type[1];
325             e.Size = type[2];
326         }
327         
328         
329         
330         row.name = e.Field;
331         
332         
333         if (typeof(map[e.Type]) == 'undefined') {
334            console.dump(e);
335            throw {
336                 name: "ArgumentError", 
337                 message: "Unknown mapping for type : " + e.Type
338             };
339         }
340         row.type = map[e.Type];
341         
342         if (row.type == 'string' && !firstTxtCol.length) {
343             firstTxtCol = row.name;
344         }
345         
346         if (row.type == 'date') {
347             row.dateFormat = 'Y-m-d';
348         }
349         reader.push(row);
350         
351         if (combofields.length == 1 && row.type == 'string') {
352             combofields.push(row);
353         }
354         
355         
356         var title = row.name.replace(/_id/, '').replace(/_/g, ' ');
357         title  = title[0].toUpperCase() + title.substring(1);
358         
359         colmodel.push({
360             "xtype": "ColumnModel",
361             "header": title,
362             "width":  row.type == 'string' ? 200 : 75,
363             "dataIndex": row.name,
364             "|renderer": row.type != 'date' ? 
365                     "function(v) { return String.format('{0}', v); }" :
366                     "function(v) { return String.format('{0}', v ? v.format('d/M/Y') : ''); }" , // special for date
367             "|xns": "Roo.grid",
368             "*prop": "colModel[]"
369         });
370         var xtype = 'TextField';
371         
372         
373         if (row.type == 'number') {
374             xtype = 'NumberField';
375         }
376         if (row.type == 'date') {
377             xtype = 'DateField';
378         }
379         if (e.Type == 'text') {
380             xtype = 'TextArea';
381         }
382         if (row.name == 'id') {
383             xtype = 'Hidden';
384         } 
385         // what about booleans.. -> checkboxes..
386         
387         
388         
389         form[row.name] = {
390             fieldLabel : title,
391             name : row.name,
392             width : row.type == 'string' ? 200 : 75,
393             '|xns' : 'Roo.form',
394             xtype : xtype
395         }
396          if (xtype == 'DateField') {
397             form[row.name].format = 'Y-m-d';
398             form[row.name].width = 100;
399         }
400         
401         if (xtype == 'TextArea') {
402             form[row.name].height = 100;
403         }
404         if (xtype == 'Hidden') {
405             delete form[row.name].fieldLabel;
406             delete form[row.name].width;
407         }
408         
409     });
410     
411     var combo = {
412         '|xns' : 'Roo.form',
413         xtype: 'ComboBox',
414         allowBlank : false,
415         editable : false,
416         emptyText : 'Select ' + table,
417         forceSelection : true,
418         listWidth : 400,
419         loadingText: 'Searching...',
420         minChars : 2,
421         pageSize : 20,
422         qtip: 'Select ' + table,
423         selectOnFocus: true,
424         triggerAction : 'all',
425         typeAhead: true,
426         
427         width: 300,
428         
429         
430         
431         tpl : '<div class="x-grid-cell-text x-btn button"><b>{name}</b> </div>', // SET WHEN USED
432         queryParam : '',// SET WHEN USED
433         fieldLabel : table,  // SET WHEN USED
434         valueField : 'id',
435         displayField : '', // SET WHEN USED eg. project_id_name
436         hiddenName : '', // SET WHEN USED eg. project_id
437         name : '', // SET WHEN USED eg. project_id_name
438         items : [
439             {
440                     
441                 '*prop' : 'store',
442                 'xtype' : 'Store',
443                 '|xns' : 'Roo.data',
444                 'remoteSort' : true,
445                 '|sortInfo' : '{ direction : \'ASC\', field: \'id\' }',
446                 listeners : {
447                     '|beforeload' : 'function (_self, o)' +
448                     "{\n" +
449                     "    o.params = o.params || {};\n" +
450                     "    // set more here\n" +
451                     "}\n"
452                 },
453                 items : [
454                     {
455                         '*prop' : 'proxy',
456                         'xtype' : 'HttpProxy',
457                         'method' : 'GET',
458                         '|xns' : 'Roo.data',
459                         '|url' : "baseURL + '/Roo/" + table + ".php'",
460                     },
461                     
462                     {
463                         '*prop' : 'reader',
464                         'xtype' : 'JsonReader',
465                         '|xns' : 'Roo.data',
466                         'id' : 'id',
467                         'root' : 'data',
468                         'totalProperty' : 'total',
469                         '|fields' : JSON.stringify(combofields)
470                         
471                     }
472                 ]
473             }
474         ]
475     }
476     
477     
478     
479     
480     //print(JSON.stringify(reader,null,4));
481     readers.push({
482         table : table ,
483         combo : combo,
484         combofields : combofields,
485         reader :  reader,
486         oreader : JSON.parse(JSON.stringify(reader)), // dupe it..
487         colmodel : colmodel,
488         firstTxtCol : firstTxtCol,
489         form : form
490     });
491     
492     //console.dump(schema );
493     
494      
495 });
496
497
498
499 // merge in the linked tables..
500 readers.forEach(function(reader) {
501     if (typeof(ini[reader.table]) == 'undefined') {
502      
503         return;
504     }
505     print("OVERLAY - " + reader.table);
506     // we have a map..
507     for (var col in ini[reader.table]) {
508         var kv = ini[reader.table][col].split(':');
509         
510         
511         var add = readers.filter(function(r) { return r.table == kv[0] })[0];
512         if (!add) {
513             continue;
514         }
515         // merge in data (eg. project_id => project_id_*****
516      
517         add.oreader.forEach(function(or) {
518             reader.reader.push({
519                 name : col + '_' + or.name,
520                 type : or.type
521             });
522         });
523         
524         // col is mapped to something..
525         var combofields = add.combofields;
526         if (add.combofields.length < 2) {
527             continue;
528         }
529         if (typeof(reader.form[col]) == 'undefined') {
530             print (JSON.stringify(reader.form, null,4));
531             print("missing linked column " + col);
532             continue;
533         }
534         
535         var combofields_name = add.combofields[1].name;
536         var old =   reader.form[col];
537         reader.form[col] = JSON.parse(JSON.stringify(add.combo)); // clone
538         reader.form[col].queryParam  = 'query[' + combofields_name + ']';// SET WHEN USED
539         reader.form[col].fieldLabel = old.fieldLabel;  // SET WHEN USED
540         reader.form[col].hiddenName = old.name; // SET WHEN USED eg. project_id
541         reader.form[col].displayField = combofields_name; // SET WHEN USED eg. project_id
542         reader.form[col].name  = old.name + '_' + combofields_name; // SET WHEN USED eg. project_id_name
543         reader.form[col].tpl = '<div class="x-grid-cell-text x-btn button"><b>{' + combofields_name +'}</b> </div>'; // SET WHEN USED
544         
545              
546     };
547     
548     
549 });
550
551 //readers.forEach(function(reader) {
552 //    delete reader.oreader;
553 //});
554
555  
556
557
558
559 //print(JSON.stringify(readers, null, 4));
560
561 readers.forEach(function(reader) {
562     
563
564     var dir = GLib.get_home_dir() + '/.Builder/Roo.data.JsonReader'; 
565     if (!File.isDirectory(dir)) {
566         print("mkdir " + dir);
567         File.mkdir(dir);
568     }
569     
570     // READERS
571     print("WRITE: " +  dir + '/' + cfg.DBNAME + '_' + reader.table + '.json');
572     
573                 
574     var jreader = {
575         '|xns' : 'Roo.data',
576         xtype : "JsonReader",
577         totalProperty : "total",
578         root : "data",
579         '*prop' : "reader",
580         id : 'id', // maybe no..
581        
582         '|fields' :  JSON.stringify(reader.reader, null,4).replace(/"/g,"'")
583     };
584     
585     File.write(
586         dir + '/' + cfg.DBNAME + '_' + reader.table + '.json',
587         JSON.stringify(jreader, null, 4)
588     )
589     
590     
591     // GRIDS
592     dir = GLib.get_home_dir() + '/.Builder/Roo.GridPanel'; 
593     if (!File.isDirectory(dir)) {
594         print("mkdir " + dir);
595         File.mkdir(dir);
596     }
597     
598
599     print("WRITE: " +  dir + '/' + cfg.DBNAME + '_' + reader.table + '.json');
600     
601     File.write(
602         dir + '/' + cfg.DBNAME + '_' + reader.table + '.json',
603             
604        
605         JSON.stringify({
606             '|xns' : 'Roo',
607             xtype : "GridPanel",
608             "title": reader.table,
609             "fitToframe": true,
610             "fitContainer": true,
611             "tableName": reader.table,
612             "background": true,
613             "region" : 'center',
614             "listeners": {
615                 "|activate": "function() {\n    _this.panel = this;\n    if (_this.grid) {\n        _this.grid.footer.onClick('first');\n    }\n}"
616             },
617             "items": [
618                 {
619                     "*prop": "grid",
620                     "xtype": "Grid",
621                     "autoExpandColumn": reader.firstTxtCol,
622                     "loadMask": true,
623                     "listeners": {
624                         "|render": "function() \n" +
625                             "{\n" +
626                             "    _this.grid = this; \n" +
627                             "    //_this.dialog = Pman.Dialog.FILL_IN\n" +
628                             "    if (_this.panel.active) {\n" +
629                             "       this.footer.onClick('first');\n" +
630                             "    }\n" +
631                             "}",
632                         "|rowdblclick": "function (_self, rowIndex, e)\n" + 
633                             "{\n" + 
634                             "    if (!_this.dialog) return;\n" + 
635                             "    _this.dialog.show( this.getDataSource().getAt(rowIndex).data, function() {\n" + 
636                             "        _this.grid.footer.onClick('first');\n" + 
637                             "    }); \n" + 
638                             "}\n"
639                     },
640                     "|xns": "Roo.grid",
641
642                     "items": [
643                         {
644                             "*prop": "dataSource",
645                             "xtype": "Store",
646                              remoteSort : true,
647                             '|sortInfo' : "{ field : '" + reader.firstTxtCol  +  "', direction: 'ASC' }", 
648                             "|xns": "Roo.data",
649                             "items": [
650                                 
651                                 {
652                                     "*prop": "proxy",
653                                     "xtype": "HttpProxy",
654                                     "method": "GET",
655                                     "|url": "baseURL + '/Roo/" + reader.table + ".php'",
656                                     "|xns": "Roo.data"
657                                 },
658                                 jreader
659                             ]
660                         },
661                         {
662                             "*prop": "footer",
663                             "xtype": "PagingToolbar",
664                             "pageSize": 25,
665                             "displayInfo": true,
666                             "displayMsg": "Displaying " + reader.table + "{0} - {1} of {2}",
667                             "emptyMsg": "No " + reader.table + " found",
668                             "|xns": "Roo"
669                         },
670                         {
671                             "*prop": "toolbar",
672                             "xtype": "Toolbar",
673                             "|xns": "Roo",
674                             "items": [
675                                 {
676                                     "text": "Add",
677                                     "xtype": "Button",
678                                     "cls": "x-btn-text-icon",
679                                     "|icon": "Roo.rootURL + 'images/default/dd/drop-add.gif'",
680                                     "listeners": {
681                                         "|click": "function()\n"+
682                                             "{\n"+
683                                             "    if (!_this.dialog) return;\n" +
684                                             "    _this.dialog.show( { id : 0 } , function() {\n"+
685                                             "        _this.grid.footer.onClick('first');\n"+
686                                             "   }); \n"+
687                                             "}\n"
688                                     },
689                                     "|xns": "Roo.Toolbar"
690                                 },
691                                 {
692                                     "text": "Edit",
693                                     "xtype": "Button",
694                                     "cls": "x-btn-text-icon",
695                                     "|icon": "Roo.rootURL + 'images/default/tree/leaf.gif'",
696                                     "listeners": {
697                                         "|click": "function()\n"+
698                                             "{\n"+
699                                             "    var s = _this.grid.getSelectionModel().getSelections();\n"+
700                                             "    if (!s.length || (s.length > 1))  {\n"+
701                                             "        Roo.MessageBox.alert(\"Error\", s.length ? \"Select only one Row\" : \"Select a Row\");\n"+
702                                             "        return;\n"+
703                                             "    }\n"+
704                                             "    if (!_this.dialog) return;\n" +
705                                             "    _this.dialog.show(s[0].data, function() {\n"+
706                                             "        _this.grid.footer.onClick('first');\n"+
707                                             "    }); \n"+
708                                             "    \n"+
709                                             "}\n" 
710                                         
711                                     },
712                                     "|xns": "Roo.Toolbar"
713                                 },
714                                 {
715                                     "text": "Delete",
716                                     "cls": "x-btn-text-icon",
717                                     "|icon": "rootURL + '/Pman/templates/images/trash.gif'",
718                                     "xtype": "Button",
719                                     "listeners": {
720                                         "|click": "function()\n"+
721                                             "{\n"+
722                                             "     Pman.genericDelete(_this, '" + reader.table + "'); \n"+
723                                             "}\n"+
724                                             "        "
725                                     },
726                                     "|xns": "Roo.Toolbar"
727                                 }
728                             ]
729                         }, // end toolbar
730                     ].concat( reader.colmodel)
731                 }
732             ]
733             
734             
735         }, null, 4)
736     )
737     
738     /// FORMS..
739     
740     dir = GLib.get_home_dir() + '/.Builder/Roo.form.Form'; 
741     if (!File.isDirectory(dir)) {
742         print("mkdir " + dir);
743         File.mkdir(dir);
744     }
745     var formElements = [];
746     var formHeight = 50;
747     for (var k in reader.form) {
748         if (k == 'id') { // should really do primary key testing..
749             continue;
750         }
751         formHeight += reader.form[k].xtype == 'TextArea' ? 100 : 30;
752         
753         formElements.push(reader.form[k]);
754     }
755     if (reader.form['id']) {
756         formElements.push(reader.form['id']);
757     }
758     
759
760     print("WRITE: " +  dir + '/' + cfg.DBNAME + '_' + reader.table + '.json');
761     var frmCfg = 
762     {
763         '|xns' : 'Roo.form',
764         xtype : "Form",
765         listeners : {
766             "|actioncomplete" : "function(_self,action)\n"+
767                 "{\n"+
768                 "    if (action.type == 'setdata') {\n"+
769                 "       //_this.dialog.el.mask(\"Loading\");\n"+
770                 "       //this.load({ method: 'GET', params: { '_id' : _this.data.id }});\n"+
771                 "       return;\n"+
772                 "    }\n"+
773                 "    if (action.type == 'load') {\n"+
774                 "        _this.dialog.el.unmask();\n"+
775                 "        return;\n"+
776                 "    }\n"+
777                 "    if (action.type =='submit') {\n"+
778                 "    \n"+
779                 "        _this.dialog.el.unmask();\n"+
780                 "        _this.dialog.hide();\n"+
781                 "    \n"+
782                 "         if (_this.callback) {\n"+
783                 "            _this.callback.call(_this, _this.form.getValues());\n"+
784                 "         }\n"+
785                 "         _this.form.reset();\n"+
786                 "         return;\n"+
787                 "    }\n"+
788                 "}\n",
789             
790             "|rendered" : "function (form)\n"+
791                 "{\n"+
792                 "    _this.form= form;\n"+
793                 "}\n"
794         },
795         method : "POST",
796         style : "margin:10px;",
797         "|url" : "baseURL + '/Roo/" + reader.table + ".php'",
798         items : formElements
799     };
800     
801     
802     File.write(
803         dir + '/' + cfg.DBNAME + '_' + reader.table + '.json',
804             
805        
806         JSON.stringify( frmCfg, null, 4)
807     );
808             
809             
810    
811    
812    
813      /// COMBO..
814     
815     dir = GLib.get_home_dir() + '/.Builder/Roo.form.ComboBox'; 
816     if (!File.isDirectory(dir)) {
817         print("mkdir " + dir);
818         File.mkdir(dir);
819     }
820    
821     print("WRITE: " +  dir + '/' + cfg.DBNAME + '_' + reader.table + '.json');
822     
823     File.write(
824         dir + '/' + cfg.DBNAME + '_' + reader.table + '.json',
825             
826        
827         JSON.stringify(reader.combo, null, 4)
828     );
829             
830    
831    
832    
833    
834    
835     // DIALOG.
836    
837    
838     dir = GLib.get_home_dir() + '/.Builder/Roo.LayoutDialog'; 
839     if (!File.isDirectory(dir)) {
840         print("mkdir " + dir);
841         File.mkdir(dir);
842     }
843     var formElements = [];
844     for (var k in reader.form) {
845         if (k == 'id') { // should really do primary key testing..
846             continue;
847         }
848         formElements.push(reader.form[k]);
849     }
850     formElements.push(reader.form['id']);
851
852     print("WRITE: " +  dir + '/' + cfg.DBNAME + '_' + reader.table + '.json');
853     
854     File.write(
855         dir + '/' + cfg.DBNAME + '_' + reader.table + '.json',
856             
857        
858         JSON.stringify({
859        
860             "closable": false,
861             "collapsible": false,
862             "height": formHeight,
863             "resizable": false,
864             "title": "Edit / Create " + reader.table,
865             "width": 400,
866             "modal" : true,
867             "xtype": "LayoutDialog",
868             "|xns": "Roo",
869             "items": [
870                 {
871                     "|xns": "Roo",
872                     "xtype": "LayoutRegion",
873                     "*prop": "center"
874                 },
875                 {
876                     "region": "center",
877                     "xtype": "ContentPanel",
878                     "|xns": "Roo",
879                     "items": [
880                         frmCfg
881                     ]
882                 },
883                 
884                 {
885                     "listeners": {
886                         "click": "function (_self, e)\n{\n    _this.dialog.hide();\n}"
887                     },
888                     "*prop": "buttons[]",
889                     "text": "Cancel",
890                     "xtype": "Button",
891                     "|xns": "Roo"
892                 },
893                 {
894                     "listeners": {
895                         "click": "function (_self, e)\n{\n    // do some checks?\n     \n    \n    _this.dialog.el.mask(\"Saving\");\n    _this.form.doAction(\"submit\");\n\n}"
896                     },
897                     "*prop": "buttons[]",
898                     "text": "Save",
899                     "xtype": "Button",
900                     "|xns": "Roo"
901                 }
902             ]
903         }, null,4)
904     );
905    
906    
907    
908 });
909
910