var crypto = require('crypto') var Step = require('step') var fs = require('fs') var _ = require('underscore') var PSQL = require(global.settings.app_root + '/app/models/psql') var spawn = require('child_process').spawn // Keeps track of what's waiting baking for export var bakingExports = {}; // Return database username from user_id // NOTE: a "null" user_id is a request to use the public user function userid_to_dbuser(user_id) { if ( _.isString(user_id) ) return _.template(global.settings.db_user, {user_id: user_id}); return global.settings.db_pubuser; }; function ogr(id) { this.id = id; } ogr.prototype = { id: "ogr", is_file: true, getQuery: function(sql, options) { return null; // dont execute the query }, transform: function(result, options, callback) { throw "should not be called for file formats" }, getContentType: function(){ return this._contentType; }, getFileExtension: function(){ return this._fileExtension; }, getKey: function(options) { return [this.id, options.dbname, options.user_id, options.gn, this.generateMD5(options.filename), this.generateMD5(options.sql)].concat(options.skipfields).join(':'); }, generateMD5: function (data){ var hash = crypto.createHash('md5'); hash.update(data); return hash.digest('hex'); } }; // Internal function usable by all OGR-driven outputs ogr.prototype.toOGR = function(options, out_format, out_filename, callback) { var dbname = options.database; var user_id = options.user_id; var gcol = options.gn; var sql = options.sql; var skipfields = options.skipfields; var out_layername = options.filename; var ogr2ogr = 'ogr2ogr'; // FIXME: make configurable var dbhost = global.settings.db_host; var dbport = global.settings.db_port; var dbuser = userid_to_dbuser(user_id); var dbpass = ''; // turn into a parameter.. var that = this; var columns = []; var geocol; var pg; // Drop ending semicolon (ogr doens't like it) sql = sql.replace(/;\s*$/, ''); Step ( function fetchColumns() { var colsql = 'SELECT * FROM (' + sql + ') as _cartodbsqlapi LIMIT 0'; pg = new PSQL(user_id, dbname, 1, 0); pg.query(colsql, this); }, function findSRS(err, result) { if (err) throw err; //if ( ! result.rows.length ) throw new Error("Query returns no rows"); var needSRS = that._needSRS; // Skip system columns, find geom column for (var i=0; i