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 : '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.' },
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 'timestamp with time zone' : 'date',
122 'timestamp without time zone' : 'date',
123 'time' : 'string', //bogus
134 'character' : 'string',
135 'character varying' : 'string',
136 'varchar' : 'string',
138 'longtext' : 'string',
139 'tinytext' : 'string',
140 'mediumtext' : 'string',
142 'timestamp' : 'number',
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 )) {
160 var groups = key_file.get_groups();
161 groups.forEach(function(g) {
164 var keys = key_file.get_keys(g);
165 if (!keys) { return; }
167 keys.forEach(function(k) {
168 print("GET val: " + k);
169 ini[g][k] = key_file.get_value(g,k);
176 if (File.isFile(cfg.INI)) {
177 if (cfg.INI.match(/links\.ini$/)) {
180 readIni(cfg.INI.replace(/\.ini$/, ".links.ini"));
185 if (File.isDirectory(cfg.INI)) {
188 //--- load ini files..
189 // this is very specific.
191 var dirs = File.list( cfg.INI + '/Pman').filter(
193 if (!File.isDirectory(cfg.INI + '/Pman/' + e + '/DataObjects')) {
201 dirs.forEach(function(d) {
202 // this currently misses the web.*/Pman/XXXX/DataObjects..
203 var path = cfg.INI + '/Pman/' + d + '/DataObjects';
205 if (!File.isDirectory(path)) {
208 var inis = File.list(path).filter(
209 function(e) { return e.match(/\.links\.ini$/); }
215 inis.forEach(function(i) {
216 readIni(path + '/' + i);
221 // look at web.XXXX/Pman/XXX/DataObjects/*.ini
222 var inis = File.list(cfg.INI).filter(
223 function(e) { return e.match(/\.links\.ini$/); }
226 inis.forEach(function(i) {
227 readIni(path + '/' + i);
233 //print(JSON.stringify(ini, null,4));
239 //GLib.key_file_load_from_file (key_file, String file, KeyFileFlags flags) : Boolean
244 query_tables = "SHOW TABLES";
245 query_describe_table = "DESCRIBE `%s`";
249 query_tables = "select c.relname FROM pg_catalog.pg_class c " +
250 "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace " +
251 "WHERE c.relkind IN ('r','') AND n.nspname NOT IN ('pg_catalog', 'pg_toast')" +
252 "AND pg_catalog.pg_table_is_visible(c.oid) ";
253 query_describe_table =
255 "f.attnum AS number, " +
256 "f.attname AS Field, " +
258 "CASE WHEN f.attnotnull = 't' THEN 'NO' ELSE 'YES' END AS isNull, " +
259 "pg_catalog.format_type(f.atttypid,f.atttypmod) AS Type, " +
260 "CASE WHEN p.contype = 'p' THEN 't' ELSE 'f' END AS primarykey, " +
261 "CASE WHEN p.contype = 'u' THEN 't' ELSE 'f' END AS uniquekey, " +
262 "CASE WHEN p.contype = 'f' THEN g.relname END AS foreignkey, " +
263 "CASE WHEN p.contype = 'f' THEN p.confkey END AS foreignkey_fieldnum, " +
264 "CASE WHEN p.contype = 'f' THEN g.relname END AS foreignkey, " +
265 "CASE WHEN p.contype = 'f' THEN p.conkey END AS foreignkey_connnum, " +
266 "CASE WHEN f.atthasdef = 't' THEN d.adsrc END AS default " +
267 "FROM pg_attribute f JOIN pg_class c ON c.oid = f.attrelid " +
268 " JOIN pg_type t ON t.oid = f.atttypid " +
269 " LEFT JOIN pg_attrdef d ON d.adrelid = c.oid AND d.adnum = f.attnum " +
270 " LEFT JOIN pg_namespace n ON n.oid = c.relnamespace " +
271 " LEFT JOIN pg_constraint p ON p.conrelid = c.oid AND f.attnum = ANY ( p.conkey ) " +
272 " LEFT JOIN pg_class AS g ON p.confrelid = g.oid " +
273 "WHERE c.relkind = 'r'::char AND n.nspname = '%n' " +
274 "AND c.relname = '%s' AND f.attnum > 0 ORDER BY number";
280 throw "Invalid data base type " + cfg.DBTYPE + " should be MySQL or PostgreSQL";
283 "Type": "varchar(255)",
284 "Null": "NO", << or is null
294 var tables = cnc.execute_select_command( query_tables).fetchAll();
295 print(JSON.stringify(tables));
298 tables.forEach(function(table) {
300 var schema = cnc.execute_select_command(
301 query_describe_table.replace(/%s/, table).replace(/%n/,'public')
307 var combofields= [ { name : 'id', type: 'int' } ]; // technically the primary key..
311 var firstTxtCol = '';
313 //print(JSON.stringify(schema, null,4)); Seed.quit();
315 schema.forEach(function(e) {
316 e.Type = e.Type || e.type;
317 e.Field = e.Field || e.field;
319 var type = e.Type.match(/([^(]+)\(([^\)]+)\)/);
331 if (typeof(map[e.Type]) == 'undefined') {
334 name: "ArgumentError",
335 message: "Unknown mapping for type : " + e.Type
338 row.type = map[e.Type];
340 if (row.type == 'string' && !firstTxtCol.length) {
341 firstTxtCol = row.name;
344 if (row.type == 'date') {
345 row.dateFormat = 'Y-m-d';
349 if (combofields.length == 1 && row.type == 'string') {
350 combofields.push(row);
354 var title = row.name.replace(/_id/, '').replace(/_/g, ' ');
355 title = title[0].toUpperCase() + title.substring(1);
358 "xtype": "ColumnModel",
360 "width": row.type == 'string' ? 200 : 75,
361 "dataIndex": row.name,
362 "|renderer": row.type != 'date' ?
363 "function(v) { return String.format('{0}', v); }" :
364 "function(v) { return String.format('{0}', v ? v.format('d/M/Y') : ''); }" , // special for date
366 "*prop": "colModel[]"
368 var xtype = 'TextField';
371 if (row.type == 'number') {
372 xtype = 'NumberField';
374 if (row.type == 'date') {
377 if (e.Type == 'text') {
380 if (row.name == 'id') {
383 // what about booleans.. -> checkboxes..
390 width : row.type == 'string' ? 200 : 75,
394 if (xtype == 'DateField') {
395 form[row.name].format = 'Y-m-d';
396 form[row.name].width = 100;
399 if (xtype == 'TextArea') {
400 form[row.name].height = 100;
402 if (xtype == 'Hidden') {
403 delete form[row.name].fieldLabel;
404 delete form[row.name].width;
414 emptyText : 'Select ' + table,
415 forceSelection : true,
417 loadingText: 'Searching...',
420 qtip: 'Select ' + table,
422 triggerAction : 'all',
429 tpl : '<div class="x-grid-cell-text x-btn button"><b>{name}</b> </div>', // SET WHEN USED
430 queryParam : '',// SET WHEN USED
431 fieldLabel : table, // SET WHEN USED
433 displayField : '', // SET WHEN USED eg. project_id_name
434 hiddenName : '', // SET WHEN USED eg. project_id
435 name : '', // SET WHEN USED eg. project_id_name
443 '|sortInfo' : '{ direction : \'ASC\', field: \'id\' }',
445 '|beforeload' : 'function (_self, o)' +
447 " o.params = o.params || {};\n" +
448 " // set more here\n" +
454 'xtype' : 'HttpProxy',
457 '|url' : "baseURL + '/Roo/" + table + ".php'",
462 'xtype' : 'JsonReader',
466 'totalProperty' : 'total',
467 '|fields' : JSON.stringify(combofields)
478 //print(JSON.stringify(reader,null,4));
482 combofields : combofields,
484 oreader : JSON.parse(JSON.stringify(reader)), // dupe it..
486 firstTxtCol : firstTxtCol,
490 //console.dump(schema );
497 // merge in the linked tables..
498 readers.forEach(function(reader) {
499 if (typeof(ini[reader.table]) == 'undefined') {
503 print("OVERLAY - " + reader.table);
505 for (var col in ini[reader.table]) {
506 var kv = ini[reader.table][col].split(':');
509 var add = readers.filter(function(r) { return r.table == kv[0] })[0];
513 // merge in data (eg. project_id => project_id_*****
515 add.oreader.forEach(function(or) {
517 name : col + '_' + or.name,
522 // col is mapped to something..
523 var combofields = add.combofields;
524 if (add.combofields.length < 2) {
527 if (typeof(reader.form[col]) == 'undefined') {
528 print (JSON.stringify(reader.form, null,4));
529 print("missing linked column " + col);
533 var combofields_name = add.combofields[1].name;
534 var old = reader.form[col];
535 reader.form[col] = JSON.parse(JSON.stringify(add.combo)); // clone
536 reader.form[col].queryParam = 'query[' + combofields_name + ']';// SET WHEN USED
537 reader.form[col].fieldLabel = old.fieldLabel; // SET WHEN USED
538 reader.form[col].hiddenName = old.name; // SET WHEN USED eg. project_id
539 reader.form[col].displayField = combofields_name; // SET WHEN USED eg. project_id
540 reader.form[col].name = old.name + '_' + combofields_name; // SET WHEN USED eg. project_id_name
541 reader.form[col].tpl = '<div class="x-grid-cell-text x-btn button"><b>{' + combofields_name +'}</b> </div>'; // SET WHEN USED
549 //readers.forEach(function(reader) {
550 // delete reader.oreader;
557 //print(JSON.stringify(readers, null, 4));
559 readers.forEach(function(reader) {
562 var dir = GLib.get_home_dir() + '/.Builder/Roo.data.JsonReader';
563 if (!File.isDirectory(dir)) {
564 print("mkdir " + dir);
569 print("WRITE: " + dir + '/' + cfg.DBNAME + '_' + reader.table + '.json');
574 xtype : "JsonReader",
575 totalProperty : "total",
578 id : 'id', // maybe no..
580 '|fields' : JSON.stringify(reader.reader, null,4).replace(/"/g,"'")
584 dir + '/' + cfg.DBNAME + '_' + reader.table + '.json',
585 JSON.stringify(jreader, null, 4)
590 dir = GLib.get_home_dir() + '/.Builder/Roo.GridPanel';
591 if (!File.isDirectory(dir)) {
592 print("mkdir " + dir);
597 print("WRITE: " + dir + '/' + cfg.DBNAME + '_' + reader.table + '.json');
600 dir + '/' + cfg.DBNAME + '_' + reader.table + '.json',
606 "title": reader.table,
608 "fitContainer": true,
609 "tableName": reader.table,
613 "|activate": "function() {\n _this.panel = this;\n if (_this.grid) {\n _this.grid.footer.onClick('first');\n }\n}"
619 "autoExpandColumn": reader.firstTxtCol,
622 "|render": "function() \n" +
624 " _this.grid = this; \n" +
625 " //_this.dialog = Pman.Dialog.FILL_IN\n" +
626 " if (_this.panel.active) {\n" +
627 " this.footer.onClick('first');\n" +
630 "|rowdblclick": "function (_self, rowIndex, e)\n" +
632 " if (!_this.dialog) return;\n" +
633 " _this.dialog.show( this.getDataSource().getAt(rowIndex).data, function() {\n" +
634 " _this.grid.footer.onClick('first');\n" +
642 "*prop": "dataSource",
645 '|sortInfo' : "{ field : '" + reader.firstTxtCol + "', direction: 'ASC' }",
651 "xtype": "HttpProxy",
653 "|url": "baseURL + '/Roo/" + reader.table + ".php'",
661 "xtype": "PagingToolbar",
664 "displayMsg": "Displaying " + reader.table + "{0} - {1} of {2}",
665 "emptyMsg": "No " + reader.table + " found",
676 "cls": "x-btn-text-icon",
677 "|icon": "Roo.rootURL + 'images/default/dd/drop-add.gif'",
679 "|click": "function()\n"+
681 " if (!_this.dialog) return;\n" +
682 " _this.dialog.show( { id : 0 } , function() {\n"+
683 " _this.grid.footer.onClick('first');\n"+
687 "|xns": "Roo.Toolbar"
692 "cls": "x-btn-text-icon",
693 "|icon": "Roo.rootURL + 'images/default/tree/leaf.gif'",
695 "|click": "function()\n"+
697 " var s = _this.grid.getSelectionModel().getSelections();\n"+
698 " if (!s.length || (s.length > 1)) {\n"+
699 " Roo.MessageBox.alert(\"Error\", s.length ? \"Select only one Row\" : \"Select a Row\");\n"+
702 " if (!_this.dialog) return;\n" +
703 " _this.dialog.show(s[0].data, function() {\n"+
704 " _this.grid.footer.onClick('first');\n"+
710 "|xns": "Roo.Toolbar"
714 "cls": "x-btn-text-icon",
715 "|icon": "rootURL + '/Pman/templates/images/trash.gif'",
718 "|click": "function()\n"+
720 " Pman.genericDelete(_this, '" + reader.table + "'); \n"+
724 "|xns": "Roo.Toolbar"
728 ].concat( reader.colmodel)
738 dir = GLib.get_home_dir() + '/.Builder/Roo.form.Form';
739 if (!File.isDirectory(dir)) {
740 print("mkdir " + dir);
743 var formElements = [];
745 for (var k in reader.form) {
746 if (k == 'id') { // should really do primary key testing..
749 formHeight += reader.form[k].xtype == 'TextArea' ? 100 : 30;
751 formElements.push(reader.form[k]);
753 if (reader.form['id']) {
754 formElements.push(reader.form['id']);
758 print("WRITE: " + dir + '/' + cfg.DBNAME + '_' + reader.table + '.json');
764 "|actioncomplete" : "function(_self,action)\n"+
766 " if (action.type == 'setdata') {\n"+
767 " //_this.dialog.el.mask(\"Loading\");\n"+
768 " //this.load({ method: 'GET', params: { '_id' : _this.data.id }});\n"+
771 " if (action.type == 'load') {\n"+
772 " _this.dialog.el.unmask();\n"+
775 " if (action.type =='submit') {\n"+
777 " _this.dialog.el.unmask();\n"+
778 " _this.dialog.hide();\n"+
780 " if (_this.callback) {\n"+
781 " _this.callback.call(_this, _this.form.getValues());\n"+
783 " _this.form.reset();\n"+
788 "|rendered" : "function (form)\n"+
790 " _this.form= form;\n"+
794 style : "margin:10px;",
795 "|url" : "baseURL + '/Roo/" + reader.table + ".php'",
801 dir + '/' + cfg.DBNAME + '_' + reader.table + '.json',
804 JSON.stringify( frmCfg, null, 4)
813 dir = GLib.get_home_dir() + '/.Builder/Roo.form.ComboBox';
814 if (!File.isDirectory(dir)) {
815 print("mkdir " + dir);
819 print("WRITE: " + dir + '/' + cfg.DBNAME + '_' + reader.table + '.json');
822 dir + '/' + cfg.DBNAME + '_' + reader.table + '.json',
825 JSON.stringify(reader.combo, null, 4)
836 dir = GLib.get_home_dir() + '/.Builder/Roo.LayoutDialog';
837 if (!File.isDirectory(dir)) {
838 print("mkdir " + dir);
841 var formElements = [];
842 for (var k in reader.form) {
843 if (k == 'id') { // should really do primary key testing..
846 formElements.push(reader.form[k]);
848 formElements.push(reader.form['id']);
850 print("WRITE: " + dir + '/' + cfg.DBNAME + '_' + reader.table + '.json');
853 dir + '/' + cfg.DBNAME + '_' + reader.table + '.json',
859 "collapsible": false,
860 "height": formHeight,
862 "title": "Edit / Create " + reader.table,
865 "xtype": "LayoutDialog",
870 "xtype": "LayoutRegion",
875 "xtype": "ContentPanel",
884 "click": "function (_self, e)\n{\n _this.dialog.hide();\n}"
886 "*prop": "buttons[]",
893 "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 "*prop": "buttons[]",