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