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