1 //<script type="text/javascript">
4 * This is a hacky generator to generate element definitions for the Roo version from the database
6 * Let's see if libgda can be used to generate our Readers for roo...
8 * Concept - conect to database..
16 * usage: seed generate.js
21 *Hack needed to latest GLib-2.0.gir
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*"/>
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*
38 GObject = imports.gi.GObject;
40 GLib = imports.gi.GLib;
42 console = imports.console;
43 File = imports.File.File;
44 Options = imports.Options.Options;
48 var prov = Gda.Config.list_providers ();
49 //print(prov.dump_as_string());
52 help_description : 'Element builder for App Builder based on database schema',
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.' },
67 var cfg = o.parse(Seed.argv);
68 print(JSON.stringify(cfg, null,4));
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);
80 Gda.DataSelect.prototype.fetchAll = function()
84 for (var i =0;i < this.get_n_columns(); i++) {
85 cols.push(this.get_column_name(i));
87 //print(JSON.stringify(cols, null,4));
88 var iter = this.create_iter();
90 //print(this.get_n_rows());
92 for (var r = 0; r < this.get_n_rows(); r++) {
96 if (cols.length == 1) {
97 res.push(this.get_value_at(0,r).get_string());
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);
121 'time' : 'string', //bogus
131 'varchar' : 'string',
133 'longtext' : 'string',
134 'tinytext' : 'string',
135 'mediumtext' : 'string',
137 'timestamp' : 'number',
146 print('Read INI : ' + fn);
147 var key_file = new GLib.KeyFile.c_new();
148 if (!key_file.load_from_file (fn , GLib.KeyFileFlags.NONE )) {
152 var groups = key_file.get_groups();
153 groups.forEach(function(g) {
156 var keys = key_file.get_keys(g);
157 if (!keys) { return; }
158 keys.forEach(function(k) {
159 ini[g][k] = key_file.get_value(g,k);
164 if (File.isFile(cfg.INI)) {
165 if (cfg.INI.match(/links\.ini$/)) {
168 readIni(cfg.INI.replace(/\.ini$/, ".links.ini"));
173 if (File.isDirectory(cfg.INI)) {
176 //--- load ini files..
177 // this is very specific.
179 var dirs = File.list( cfg.INI + '/Pman').filter(
181 if (!File.isDirectory(cfg.INI + '/Pman/' + e + '/DataObjects')) {
189 dirs.forEach(function(d) {
190 // this currently misses the web.*/Pman/XXXX/DataObjects..
191 var path = cfg.INI + '/Pman/' + d + '/DataObjects';
193 if (!File.isDirectory(path)) {
196 var inis = File.list(path).filter(
197 function(e) { return e.match(/\.links\.ini$/); }
203 inis.forEach(function(i) {
204 readIni(path + '/' + i);
209 // look at web.XXXX/Pman/XXX/DataObjects/*.ini
210 var inis = File.list(cfg.INI).filter(
211 function(e) { return e.match(/\.links\.ini$/); }
214 inis.forEach(function(i) {
215 readIni(path + '/' + i);
221 //print(JSON.stringify(ini, null,4));
227 //GLib.key_file_load_from_file (key_file, String file, KeyFileFlags flags) : Boolean
232 query_tables = "SHOW TABLES";
233 query_describe_table = "DESCRIBE `%s`";
237 query_tables = "select c.relname FROM pg_catalog.pg_class c " +
238 "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace " +
239 "WHERE c.relkind IN ('r','') AND n.nspname NOT IN ('pg_catalog', 'pg_toast')" +
240 "AND pg_catalog.pg_table_is_visible(c.oid) ";
241 query_describe_table =
243 "f.attnum AS number, " +
244 "f.attname AS Field, " +
246 "CASE WHEN f.attnotnull = 't' THEN 'NO' ELSE 'YES' END AS isNull, " +
247 "pg_catalog.format_type(f.atttypid,f.atttypmod) AS Type, " +
248 "CASE WHEN p.contype = 'p' THEN 't' ELSE 'f' END AS primarykey, " +
249 "CASE WHEN p.contype = 'u' THEN 't' ELSE 'f' END AS uniquekey, " +
250 "CASE WHEN p.contype = 'f' THEN g.relname END AS foreignkey, " +
251 "CASE WHEN p.contype = 'f' THEN p.confkey END AS foreignkey_fieldnum, " +
252 "CASE WHEN p.contype = 'f' THEN g.relname END AS foreignkey, " +
253 "CASE WHEN p.contype = 'f' THEN p.conkey END AS foreignkey_connnum, " +
254 "CASE WHEN f.atthasdef = 't' THEN d.adsrc END AS default " +
255 "FROM pg_attribute f JOIN pg_class c ON c.oid = f.attrelid " +
256 " JOIN pg_type t ON t.oid = f.atttypid " +
257 " LEFT JOIN pg_attrdef d ON d.adrelid = c.oid AND d.adnum = f.attnum " +
258 " LEFT JOIN pg_namespace n ON n.oid = c.relnamespace " +
259 " LEFT JOIN pg_constraint p ON p.conrelid = c.oid AND f.attnum = ANY ( p.conkey ) " +
260 " LEFT JOIN pg_class AS g ON p.confrelid = g.oid " +
261 "WHERE c.relkind = 'r'::char AND n.nspname = '%n' " +
262 "AND c.relname = '%s' AND f.attnum > 0 ORDER BY number";
269 "Type": "varchar(255)",
270 "Null": "NO", << or is null
280 var tables = Gda.execute_select_command(cnc, query_tables).fetchAll();
281 print(JSON.stringify(tables));
284 tables.forEach(function(table) {
286 var schema = Gda.execute_select_command(cnc,
287 query_describe_table.replace(/%s/, table).replace(/%n/,'public')
293 var combofields= [ { name : 'id', type: 'int' } ]; // technically the primary key..
297 var firstTxtCol = '';
299 //print(JSON.stringify(schema, null,4)); Seed.quit();
301 schema.forEach(function(e) {
302 var type = e.Type.match(/([^(]+)\(([^\)]+)\)/);
314 if (typeof(map[e.Type]) == 'undefined') {
317 name: "ArgumentError",
318 message: "Unknown mapping for type : " + e.Type
321 row.type = map[e.Type];
323 if (row.type == 'string' && !firstTxtCol.length) {
324 firstTxtCol = row.name;
327 if (row.type == 'date') {
328 row.dateFormat = 'Y-m-d';
332 if (combofields.length == 1 && row.type == 'string') {
333 combofields.push(row);
337 var title = row.name.replace(/_id/, '').replace(/_/g, ' ');
338 title = title[0].toUpperCase() + title.substring(1);
341 "xtype": "ColumnModel",
343 "width": row.type == 'string' ? 200 : 75,
344 "dataIndex": row.name,
345 "|renderer": row.type != 'date' ?
346 "function(v) { return String.format('{0}', v); }" :
347 "function(v) { return String.format('{0}', v ? v.format('d/M/Y') : ''); }" , // special for date
349 "*prop": "colModel[]"
351 var xtype = 'TextField';
354 if (row.type == 'number') {
355 xtype = 'NumberField';
357 if (row.type == 'date') {
360 if (e.Type == 'text') {
363 if (row.name == 'id') {
366 // what about booleans.. -> checkboxes..
373 width : row.type == 'string' ? 200 : 75,
377 if (xtype == 'TextArea') {
378 form[row.name].height = 100;
380 if (xtype == 'Hidden') {
381 delete form[row.name].fieldLabel;
382 delete form[row.name].width;
390 allowBlank : 'false',
392 emptyText : 'Select ' + table,
393 forceSelection : true,
395 loadingText: 'Searching...',
398 qtip: 'Select ' + table,
400 triggerAction : 'all',
407 tpl : '<div class="x-grid-cell-text x-btn button"><b>{name}</b> </div>', // SET WHEN USED
408 queryParam : '',// SET WHEN USED
409 fieldLabel : table, // SET WHEN USED
411 displayField : '', // SET WHEN USED eg. project_id_name
412 hiddenName : '', // SET WHEN USED eg. project_id
413 name : '', // SET WHEN USED eg. project_id_name
421 '|sortInfo' : '{ direction : \'ASC\', field: \'id\' }',
423 '|beforeload' : 'function (_self, o)' +
425 " o.params = o.params || {};\n" +
426 " // set more here\n" +
432 'xtype' : 'HttpProxy',
435 '|url' : "baseURL + '/Roo/" + table + ".php'",
440 'xtype' : 'JsonReader',
444 'totalProperty' : 'total',
445 '|fields' : JSON.stringify(combofields)
456 //print(JSON.stringify(reader,null,4));
460 combofields : combofields,
462 oreader : JSON.parse(JSON.stringify(reader)), // dupe it..
464 firstTxtCol : firstTxtCol,
468 //console.dump(schema );
475 // merge in the linked tables..
476 readers.forEach(function(reader) {
477 if (typeof(ini[reader.table]) == 'undefined') {
481 print("OVERLAY - " + reader.table);
483 for (var col in ini[reader.table]) {
484 var kv = ini[reader.table][col].split(':');
487 var add = readers.filter(function(r) { return r.table == kv[0] })[0];
491 // merge in data (eg. project_id => project_id_*****
493 add.oreader.forEach(function(or) {
495 name : col + '_' + or.name,
500 // col is mapped to something..
501 var combofields = add.combofields;
502 if (add.combofields.length < 2) {
505 if (typeof(reader.form[col]) == 'undefined') {
506 print (JSON.stringify(reader.form, null,4));
507 print("missing linked column " + col);
511 var combofields_name = add.combofields[1].name;
512 var old = reader.form[col];
513 reader.form[col] = JSON.parse(JSON.stringify(add.combo)); // clone
514 reader.form[col].queryParam = 'query[' + combofields_name + ']';// SET WHEN USED
515 reader.form[col].fieldLabel = old.fieldLabel; // SET WHEN USED
516 reader.form[col].hiddenName = old.name; // SET WHEN USED eg. project_id
517 reader.form[col].displayField = combofields_name; // SET WHEN USED eg. project_id
518 reader.form[col].name = old.name + '_' + combofields_name; // SET WHEN USED eg. project_id_name
519 reader.form[col].tpl = '<div class="x-grid-cell-text x-btn button"><b>{' + combofields_name +'}</b> </div>'; // SET WHEN USED
527 //readers.forEach(function(reader) {
528 // delete reader.oreader;
535 //print(JSON.stringify(readers, null, 4));
537 readers.forEach(function(reader) {
540 var dir = GLib.get_home_dir() + '/.Builder/Roo.data.JsonReader';
541 if (!File.isDirectory(dir)) {
542 print("mkdir " + dir);
547 print("WRITE: " + dir + '/' + cfg.DBNAME + '_' + reader.table + '.json');
552 xtype : "JsonReader",
553 totalProperty : "total",
556 id : 'id', // maybe no..
558 '|fields' : JSON.stringify(reader.reader, null,4).replace(/"/g,"'")
562 dir + '/' + cfg.DBNAME + '_' + reader.table + '.json',
563 JSON.stringify(jreader, null, 4)
568 dir = GLib.get_home_dir() + '/.Builder/Roo.GridPanel';
569 if (!File.isDirectory(dir)) {
570 print("mkdir " + dir);
575 print("WRITE: " + dir + '/' + cfg.DBNAME + '_' + reader.table + '.json');
578 dir + '/' + cfg.DBNAME + '_' + reader.table + '.json',
584 "title": reader.table,
586 "fitContainer": true,
587 "tableName": reader.table,
591 "|activate": "function() {\n _this.panel = this;\n if (_this.grid) {\n _this.grid.footer.onClick('first');\n }\n}"
597 "autoExpandColumn": reader.firstTxtCol,
600 "|render": "function() \n" +
602 " _this.grid = this; \n" +
603 " //_this.dialog = Pman.Dialog.FILL_IN\n" +
604 " if (_this.panel.active) {\n" +
605 " this.footer.onClick('first');\n" +
608 "|rowdblclick": "function (_self, rowIndex, e)\n" +
610 " if (!_this.dialog) return;\n" +
611 " _this.dialog.show( this.getDataSource().getAt(rowIndex), function() {\n" +
612 " _this.grid.footer.onClick('first');\n" +
620 "*prop": "dataSource",
623 '|sortInfo' : "{ field : '" + reader.firstTxtCol + "', direction: 'ASC' }",
629 "xtype": "HttpProxy",
631 "|url": "baseURL + '/Roo/" + reader.table + ".php'",
639 "xtype": "PagingToolbar",
642 "displayMsg": "Displaying " + reader.table + "{0} - {1} of {2}",
643 "emptyMsg": "No " + reader.table + " found",
654 "cls": "x-btn-text-icon",
655 "|icon": "Roo.rootURL + 'images/default/dd/drop-add.gif'",
657 "|click": "function()\n"+
659 " if (!_this.dialog) return;\n" +
660 " _this.dialog.show( { id : 0 } , function() {\n"+
661 " _this.grid.footer.onClick('first');\n"+
665 "|xns": "Roo.Toolbar"
670 "cls": "x-btn-text-icon",
671 "|icon": "Roo.rootURL + 'images/default/tree/leaf.gif'",
673 "|click": "function()\n"+
675 " var s = _this.grid.getSelectionModel().getSelections();\n"+
676 " if (!s.length || (s.length > 1)) {\n"+
677 " Roo.MessageBox.alert(\"Error\", s.length ? \"Select only one Row\" : \"Select a Row\");\n"+
680 " if (!_this.dialog) return;\n" +
681 " _this.dialog.show(s[0].data, function() {\n"+
682 " _this.grid.footer.onClick('first');\n"+
688 "|xns": "Roo.Toolbar"
692 "cls": "x-btn-text-icon",
693 "|icon": "rootURL + '/Pman/templates/images/trash.gif'",
696 "|click": "function()\n"+
698 " Pman.genericDelete(_this, '" + reader.table + "'); \n"+
702 "|xns": "Roo.Toolbar"
706 ].concat( reader.colmodel)
716 dir = GLib.get_home_dir() + '/.Builder/Roo.form.Form';
717 if (!File.isDirectory(dir)) {
718 print("mkdir " + dir);
721 var formElements = [];
723 for (var k in reader.form) {
724 if (k == 'id') { // should really do primary key testing..
727 formHeight += reader.form[k].xtype == 'TextArea' ? 100 : 30;
729 formElements.push(reader.form[k]);
731 if (reader.form['id']) {
732 formElements.push(reader.form['id']);
736 print("WRITE: " + dir + '/' + cfg.DBNAME + '_' + reader.table + '.json');
742 "|actioncomplete" : "function(_self,action)\n"+
744 " if (action.type == 'setdata') {\n"+
745 " //_this.dialog.el.mask(\"Loading\");\n"+
746 " //this.load({ method: 'GET', params: { '_id' : _this.data.id }});\n"+
749 " if (action.type == 'load') {\n"+
750 " _this.dialog.el.unmask();\n"+
753 " if (action.type =='submit') {\n"+
755 " _this.dialog.el.unmask();\n"+
756 " _this.dialog.hide();\n"+
758 " if (_this.callback) {\n"+
759 " _this.callback.call(_this, _this.form.getValues());\n"+
761 " _this.form.reset();\n"+
766 "|rendered" : "function (form)\n"+
768 " _this.form= form;\n"+
772 style : "margin:10px;",
773 "|url" : "baseURL + '/Roo/" + reader.table + ".php'",
779 dir + '/' + cfg.DBNAME + '_' + reader.table + '.json',
782 JSON.stringify( frmCfg, null, 4)
791 dir = GLib.get_home_dir() + '/.Builder/Roo.form.ComboBox';
792 if (!File.isDirectory(dir)) {
793 print("mkdir " + dir);
797 print("WRITE: " + dir + '/' + cfg.DBNAME + '_' + reader.table + '.json');
800 dir + '/' + cfg.DBNAME + '_' + reader.table + '.json',
803 JSON.stringify(reader.combo, null, 4)
814 dir = GLib.get_home_dir() + '/.Builder/Roo.LayoutDialog';
815 if (!File.isDirectory(dir)) {
816 print("mkdir " + dir);
819 var formElements = [];
820 for (var k in reader.form) {
821 if (k == 'id') { // should really do primary key testing..
824 formElements.push(reader.form[k]);
826 formElements.push(reader.form['id']);
828 print("WRITE: " + dir + '/' + cfg.DBNAME + '_' + reader.table + '.json');
831 dir + '/' + cfg.DBNAME + '_' + reader.table + '.json',
837 "collapsible": false,
838 "height": formHeight,
840 "title": "Edit / Create " + reader.table,
842 "xtype": "LayoutDialog",
847 "xtype": "LayoutRegion",
852 "xtype": "ContentPanel",
861 "click": "function (_self, e)\n{\n _this.dialog.hide();\n}"
863 "*prop": "buttons[]",
870 "click": "function (_self, e)\n{\n // do some checks?\n \n \n _this.dialog.el.mask(\"Saving\");\n _this.form.doAction(\"submit\");\n\n}"
872 "*prop": "buttons[]",