Push a CouchApp to a CouchDB database.

@param  {String} db
@param  {Object} opts
@return {Stream}
179316
function pushCouchapp(dbName, opts) {
  opts = opts || {}

  if (!dbName && typeof dbName !== 'string') {
    throw new PluginError(PLUGIN_NAME, 'Missing database name.');
  }

  return through.obj(function (file, enc, cb) {
    var ddocObj = require(file.path)
    var url = /^https?:\/\//.test(dbName) ? dbName : buildURL(dbName, opts);

    if (file.isNull()) {
      return cb(null, file)
    }

    if (file.isStream()) {
      this.emit('error', new PluginError(PLUGIN_NAME, 'Streaming not supported.'))
      return cb(null, file)
    }

    if (path.extname(file.path) !== '.js') {
      this.emit('error', new PluginError(PLUGIN_NAME, 'File extension not supported.'))
      return cb(null, file)
    }

    if (has(opts, 'attachments')) {
      var attachmentsPath = path.join(process.cwd(), path.normalize(opts.attachments))
      couchapp.loadAttachments(ddocObj, attachmentsPath)
    }

    couchapp.createApp(ddocObj, url, function (app) {
      app.push(function () {
        gutil.log(PLUGIN_NAME, 'Couchapp pushed!')
        return cb(null, file)
      })
    })
  })
}
1290794
function create_watchdog(db, opts) {
	debug.assert(db).is('object');

	opts = opts || {};

	debug.assert(opts).is('object');

	opts.timeout = opts.timeout || 30000;
	debug.assert(opts.timeout).is('number');

	var w = {};
	w.db = db;
	w.opts = opts;

	/* Setup */

	w.timeout = setTimeout(function() {
		debug.warn('Got timeout.');
		w.timeout = undefined;
		Q.fcall(function() {
			var tr_open, tr_commit, tr_rollback, state, tr_unknown, tr_disconnect;

			// NoPg instance
			if(w.db === undefined) {
				debug.warn("Timeout exceeded and database instance undefined. Nothing done.");
				return;
			}

			if(!(w.db && w.db._tr_state)) {
				debug.warn("Timeout exceeded but db was not NoPg instance.");
				return;
			}

			state = w.db._tr_state;
			tr_open = (state === 'open') ? true : false;
			tr_commit = (state === 'commit') ? true : false;
			tr_rollback = (state === 'rollback') ? true : false;
			tr_disconnect = (state === 'disconnect') ? true : false;
			tr_unknown = ((!tr_open) && (!tr_commit) && (!tr_rollback) && (!tr_disconnect)) ? true : false;

			if(tr_unknown) {
				debug.warn("Timeout exceeded and transaction state was unknown ("+state+"). Nothing done.");
				return;
			}

			if(tr_open) {
				debug.warn("Timeout exceeded and transaction still open. Closing it by rollback.");
				return w.db.rollback().fail(function(err) {
					debug.error("Rollback failed: " + (err.stack || err) );
				});
			}

			if(tr_disconnect) {
				//debug.log('...but .disconnect() was already done.');
				return;
			}

			if(tr_commit) {
				//debug.log('...but .commit() was already done.');
				return;
			}

			if(tr_rollback) {
				//debug.log('...but .rollback() was already done.');
				return;
			}

		}).fin(function() {
			if(w && w.db) {
				w.db._events.emit('timeout');
			}
		}).done();
	}, opts.timeout);

	/* Set object */
	w.reset = function(o) {
		debug.assert(o).is('object');
		//debug.log('Resetting the watchdog.');
		w.db = o;
	};

	/** Clear the timeout */
	w.clear = function() {
		if(w.timeout) {
			//debug.log('Clearing the watchdog.');
			clearTimeout(w.timeout);
			w.timeout = undefined;
		}
	};

	return w;
}
1343575
@NonNull
    public static As database(@NonNull com.couchbase.lite.Database database) {
        if (database == null) {
            throw new IllegalArgumentException("database cannot be null.");
        }
        return new As(database);
    }
289130
function putDB(cb) {
    request.put({url: db_url}, function(error, response, body) {
      if (error) {
        console.log("Error creating DB: " + error);
      } else {
        cb();
      }
    });
  }
1167527
function(db, opt_err) {

    if (df.hasFired()) {
      goog.log.warning(me.logger, 'database already set.');
    } else if (goog.isDef(opt_err)) {
      goog.log.warning(me.logger, opt_err ? opt_err.message : 'Error received.');
      me.idx_db_ = null;
      df.errback(opt_err);
    } else {
      goog.asserts.assertObject(db, 'db');
      me.idx_db_ = db;
      me.idx_db_.onabort = function(e) {
        goog.log.finest(me.logger, me + ': abort');
        var request = /** @type {IDBRequest} */ (e.target);
        me.onError(request.error);
      };
      me.idx_db_.onerror = function(e) {
        if (ydn.db.con.IndexedDb.DEBUG) {
          goog.global.console.log(e);
        }
        goog.log.finest(me.logger, me + ': error');
        var request = /** @type {IDBRequest} */ (e.target);
        me.onError(request.error);
      };

      /**
       * @this {null}
       * @param {IDBVersionChangeEvent} event event.
       */
      me.idx_db_.onversionchange = function(event) {
        // Handle version changes while a web app is open in another tab
        // https://developer.mozilla.org/en-US/docs/IndexedDB/Using_IndexedDB#
        // Version_changes_while_a_web_app_is_open_in_another_tab
        //
        if (ydn.db.con.IndexedDb.DEBUG) {
          goog.global.console.log([this, event]);
        }
        goog.log.finest(me.logger, me + ' closing connection for onversionchange to: ' +
            event.version);
        if (me.idx_db_) {
          me.idx_db_.onabort = null;
          me.idx_db_.onblocked = null;
          me.idx_db_.onerror = null;
          me.idx_db_.onversionchange = null;
          me.onVersionChange(event);
          if (!event.defaultPrevented) {
            me.idx_db_.close();
            me.idx_db_ = null;
            var e = new Error();
            e.name = event.type;
            me.onFail(e);
          }
        }
      };
      df.callback(parseFloat(old_version));
    }

  }
1329413
function pubServer(opts) {

  if (!(this instanceof pubServer)) return new pubServer(opts);
  events.EventEmitter.call(this);

  var server = this;

  // pass platform-specific ./node_modules path to resolve-opts for builtin packages
  server.opts = opts = require('pub-resolve-opts')(opts, path.join(__dirname, 'node_modules'));

  opts.production  = opts.production || (process.env.NODE_ENV === 'production');
  opts.port        = opts.port       || process.env.PORT || '3001';
  opts.appUrl      = opts.appUrl     || process.env.APP  || ('http://localhost:' + opts.port);

  server.run       = run;

  var generator = server.generator = require('pub-generator')(opts);

  u.each(opts.serverPlugins.reverse(), function(plugin) {
    debug('server plugin:', plugin.inspect());
    require(plugin.path)(server);
  });

  u.each(opts.generatorPlugins.reverse(), function(plugin) {
    debug('generator plugin:', plugin.path, plugin.inspect());
    require(plugin.path)(generator);
  });

  var log = opts.log;

  //--//--//--//--//--//--//--//--//--//--//--//

  function run() {
    generator.load(function(err) {
      if (err) return log(err);

      if (opts.outputOnly) {
        generator.outputPages(function(err, result) {
          if (err) { log(err); }
          log('output %s generated pages', u.flatten(result).length);
        });

        var statics = require('./server/serve-statics')(opts, function(){
          statics.outputAll();
        });
        require('./server/serve-scripts')(opts).outputAll(generator);
        generator.unload();
        return;
      }

      if (opts.logPages) {
        generator.logPages();
        generator.unload();
        return;
      }

      require('./server/watch-sources')(generator);
      generator.listen(true);

      if (!opts['no-server']) { expressApp(); }
    });
  }

  function expressApp() {

    server.app =  require('express')();
    server.http = require('http').Server(server.app);
    require('./server/serve-sockets')(server);

    server.app.disable('x-powered-by');

    // log(err) shouldn't throw anymore
    log.logger.noErrors = true;

    // sessions come with optional redis logger
    server.sessions = require('pub-serve-sessions')(server);
    log('starting up', opts.appUrl);

    // other default middleware
    var bodyParser = require('body-parser');
    server.app.use(bodyParser.json());
    server.app.use(bodyParser.urlencoded({ extended: false }));
    server.app.use(require('compression')());

    server.emit('init-app-first');
    server.sessions.authorizeRoutes();

    if (!opts.staticOnly) {
      require('./server/serve-pages')(server);
      server.scripts = require('./server/serve-scripts')(opts).serveRoutes(server);
    }
    server.statics = require('./server/serve-statics')(opts).serveRoutes(server);

    server.emit('init-app-last');

    require('./server/handle-errors')(server);

    server.http.listen(opts.port);
    log('listening on port', opts.port);

    process.on('SIGTERM', function() {
      log('shutting down');
      server.http.close(function() {
        generator.unload();
        server.emit('shutdown');
        process.exit();
      });
    });

  }

}
963999
function AsyncStorageCore(dbname, opts = DEFAULT_OPTS) {
  this._prefix = createPrefix(dbname);
  this._asyncStorageImpl = opts.AsyncStorage
}
1229843
function _initStorage(options) {
	        var self = this;
	        var dbInfo = {
	            db: null
	        };

	        if (options) {
	            for (var i in options) {
	                dbInfo[i] = typeof options[i] !== 'string' ? options[i].toString() : options[i];
	            }
	        }

	        var dbInfoPromise = new Promise(function (resolve, reject) {
	            // Open the database; the openDatabase API will automatically
	            // create it for us if it doesn't exist.
	            try {
	                dbInfo.db = openDatabase(dbInfo.name, String(dbInfo.version), dbInfo.description, dbInfo.size);
	            } catch (e) {
	                return self.setDriver(self.LOCALSTORAGE).then(function () {
	                    return self._initStorage(options);
	                }).then(resolve)['catch'](reject);
	            }

	            // Create our key/value table if it doesn't exist.
	            dbInfo.db.transaction(function (t) {
	                t.executeSql('CREATE TABLE IF NOT EXISTS ' + dbInfo.storeName + ' (id INTEGER PRIMARY KEY, key unique, value)', [], function () {
	                    self._dbInfo = dbInfo;
	                    resolve();
	                }, function (t, error) {
	                    reject(error);
	                });
	            });
	        });

	        return new Promise(function (resolve, reject) {
	            resolve(__webpack_require__(3));
	        }).then(function (lib) {
	            dbInfo.serializer = lib;
	            return dbInfoPromise;
	        });
	    }
346697
function serve(app, couch) {
  var url = require('url');
  var port = 3000,
      staticDir = 'attachments',
      tmpDir = '/tmp/couchapp-compile-' + process.pid,
      logDbRewrites = false;
  var arg;
  while(arg = process.argv.shift()){
    if(arg == '-p'){
      port = parseInt(process.argv.shift());
    }
    if(arg == '-d'){
      staticDir = process.argv.shift();
    }
    if(arg == '-l'){
      logDbRewrites = true;
    }
  }
  var dbUrlObj = url.parse(couch);

  var proxyPaths = {}
  var dbPrefix = '../../';
  for (var i in app.doc.rewrites){
    var rw = app.doc.rewrites[i];
    // Rewrites starting with '../../' are proxied to the database
    if (rw.to.indexOf(dbPrefix) == 0){
      var proxyPath = rw.from;
      if(proxyPath[proxyPath.length -1] == '*') {
        proxyPath = proxyPath.substring(0,proxyPath.length-1)
      }
      var dbPath = rw.to.substring(dbPrefix.length);
      if(dbPath[dbPath.length - 1] == '*'){
        dbPath = dbPath.substring(0,dbPath.length-1)
      }
      if(dbPath.indexOf('*') >=0 ){
        if(logDbRewrites){
          console.log("Don't know how to proxy '" + rw.from + "' to CouchDB at " + rw.from );
        }
      } else {
        proxyPaths[proxyPath] =
          dbUrlObj.protocol + '//' + dbUrlObj.host +
          path.normalize(dbUrlObj.pathname + dbPath);
          if(logDbRewrites){
            console.log("Proxying rewrite '" + proxyPath + "' to CouchDB at " + proxyPaths[proxyPath] );
          }
      }
    }
  }

  var connect = require('connect');
  var httpProxy = require('http-proxy'),
      connect   = require('connect'),
      logger = require('morgan'),
      serveStatic = require('serve-static'),
      errorHandler = require('errorhandler'),
      connectCompiler;
  try{
      connectCompiler = require('connect-compiler');
  } catch(e) {}


  var proxy = httpProxy.createProxyServer({
    target: {
      host: dbUrlObj.host,
      hostname: dbUrlObj.hostname,
      port: dbUrlObj.port,
      https: dbUrlObj.protocol == 'https:',
    }
  });
  var app = connect()
    .use(logger('dev'))
    .use(serveStatic(staticDir));
  if(connectCompiler){
    console.log('Will compile assets with connect-assets.');
    var ignore = [];
    var quote = function(str) {
      return (str+'').replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1");
    }
    for(var prefix in proxyPaths){
      ignore.push(quote(prefix));
    }
    if(ignore.length){
      //console.log("Asset compile ignore paths:", '^(' +  ignore.join('|') + ')');
      ignore  = new RegExp('^(' +  ignore.join('|') + ')');
    } else {
      ignore = null;
    }
    app.use(connectCompiler({
      enabled: ['coffee'] ,
      src: staticDir,
      dest: tmpDir,
      ignore :  ignore,
    }))
    .use(serveStatic(tmpDir));
  }
  app.use(function(req, res, next) {
      for(var prefix in proxyPaths){
        var dbPath = proxyPaths[prefix];
        if (req.url.indexOf(prefix) === 0) {
          var dbURL = req.url.replace(prefix,dbPath);
          if(logDbRewrites){
            console.log("*** ", req.url , ' -> ', dbURL);
          }
          req.url = dbURL;
          req.headers['host'] = dbUrlObj.host;
          proxy.proxyRequest(req, res);
          return;
        }
      }
      var body = '404 Not found.\nNo static file or db route matched.';
      res.statusCode = 404;
      res.setHeader('Content-Length', body.length);
      res.end(body);
     })
    .use(errorHandler())
    .listen(port);
  console.log("Serving couchapp at: http://0.0.0.0:" + port +"/");

  //Cleanup the temp directory on exit
  var cleanup = function(){
    var rmDir = function(dirPath) {
      try { var files = fs.readdirSync(dirPath); }
      catch(e) { return; }
      if (files.length > 0)
        for (var i = 0; i < files.length; i++) {
          var filePath = dirPath + '/' + files[i];
          if (fs.statSync(filePath).isFile())
            fs.unlinkSync(filePath);
          else
            rmDir(filePath);
        }
      fs.rmdirSync(dirPath);
    };
    rmDir(tmpDir);
  };
  process.on('exit',cleanup);
  process.on('SIGINT',function(){
    cleanup()
    process.exit();
  });
}
432109
function(dbOrUri, stream, callback) {
    var db;
    if (arguments.length === 2) {
      callback = stream;
      stream = undefined;
    }
    if (!stream) {
      stream = process.stdin;
    }

    var state = 'start';
    var version;
    var collection;
    var endOfCollection;
    var insertQueue = [];
    var insertQueueSize = 0;

    // State machine

    var processors = {
      start: function(item, callback) {
        try {
          item = BSON.deserialize(item);
        } catch (e) {
          return callback(e);
        }
        if (typeof(item) !== 'object') {
          return callback(new Error('First BSON element is not an object'));
        }
        if (item.type !== 'mongo-dump-stream') {
          return callback(new Error('type property is not mongo-dump-stream'));
        }
        version = item.version;
        if (item.version > 2) {
          return callback(new Error('Incoming mongo-dump-stream is of a newer version, bailing out'));
        }
        endOfCollection = item.endOfCollection;
        state = 'collection';
        return callback(null);
      },
      collection: function(item, callback) {
        try {
          item = BSON.deserialize(item);
        } catch (e) {
          return callback(e);
        }
        if (item.type === 'endDatabase') {
          state = 'done';
          return callback(null);
        }
        if (item.type !== 'collection') {
          return callback(new Error('collection expected'));
        }
        var name = item.name;
        var indexes = item.indexes;
        async.series({
          create: function(callback) {
            return db.collection(name, function(err, _collection) {
              if (err) {
                return callback(err);
              }
              collection = _collection;
              return callback(null);
            });
          },
          indexes: function(callback) {
            return async.eachSeries(item.indexes, function(item, callback) {
              if (item.name === '_id_') {
                // automatic
                return setImmediate(callback);
              }
              return collection.ensureIndex(item.key, _.omit(item, 'ns', 'key'), callback);
            }, callback);
          }
        }, function(err) {
          if (err) {
            return callback(err);
          }
          state = 'documents';
          return callback(null);
        });
      },
      documents: function(item, callback) {
        if (version === '1') {
          item = BSON.deserialize(item);
          if (item.type === 'endCollection') {
            state = 'collection';
            return setImmediate(callback);
          }
          if (item.type !== 'document') {
            return callback(new Error('Document expected'));
          }
          return collection.insert(item.document, callback);
        }

        // Just scan for the unique random string that
        // appears in the end-of-collection object. No need
        // to waste time parsing BSON for this. Also
        // leverage the fact that it won't ever be
        // part of a large object to avoid scanning them all
        if (item.length < 100) {
          if (buffertools.indexOf(item, endOfCollection) !== -1) {
            return flush(function(err) {
              if (err) {
                return callback(err);
              }
              state = 'collection';
              return callback(null);
            });
          }
        }
        return async.series({
          flushIfNeeded: function(callback) {
            if (insertQueueSize + item.length <= 16777216) {
              return setImmediate(callback);
            }
            return flush(callback);
          },
          insertInQueue: function(callback) {
            insertQueueSize += item.length;
            insertQueue.push(item);
            return setImmediate(callback);
          }
        }, callback);

        function flush(callback) {
          if (!insertQueue.length) {
            // MongoDB considers it an error to be asked
            // to insert 0 documents ):
            return setImmediate(callback);
          }
          // watch out for race condition
          var insert = insertQueue;
          insertQueue = [];
          insertQueueSize = 0;
          return collection.insert(insert, function(err) {
            insertQueue = [];
            return callback(err);
          });
        }
      }
    };

    return async.series({
      connect: function(callback) {
        if (typeof(dbOrUri) !== 'string') {
          // Already a mongodb connection
          db = dbOrUri;
          return setImmediate(callback);
        }
        return mongodb.MongoClient.connect(dbOrUri, function(err, _db) {
          if (err) {
            return callback(err);
          }
          db = _db;
          return callback(null);
        });
      },
      dropCollections: function(callback) {
        return db.collections(function(err, collections) {
          if (err) {
            return callback(err);
          }
          return async.eachSeries(collections, function(item, callback) {
            if (item.collectionName.match(/^system\./)) {
              return setImmediate(callback);
            }
            return item.drop(callback);
          }, callback);
        });
      },
      loadCollections: function(finalCallback) {
        return reader({ raw: true, from: stream }, function(doc, callback) {
          return processors[state](doc, function(err) {
            if (err) {
              return callback(err);
            }
            if (state === 'done') {
              return finalCallback(null);
            }
            return callback(null);
          });
        }, function(err) {
          if (err) {
            return finalCallback(err);
          }
          return finalCallback(new Error('Premature end of stream'));
        });
      }
    }, callback);
  }
613136
function createDb (dbName, qs0, callback0) {
    const { opts, callback } = getCallback(qs0, callback0)
    return relax({ db: dbName, method: 'PUT', qs: opts }, callback)
  }
1137253
function (dag, opts) {
  var since = opts.since || 0
  var limit = opts.limit || -1
  var wait = null

  var read = function (size, cb) {
    if (dag.changes <= since) {
      wait = cb
      return
    }

    if (!limit) return cb(null, null)

    dag.db.get(CHANGES + lexint.pack(since + 1, 'hex'), function (err, hash) {
      if (err) return cb(err)
      dag.get(hash, opts, function (err, node) {
        if (err) return cb(err)
        since = node.change
        if (limit !== -1) limit--
        cb(null, node)
      })
    })
  }

  var kick = function () {
    if (!wait) return
    var cb = wait
    wait = null
    read(0, cb)
  }

  dag.on('add', kick)
  dag.ready(kick)

  var rs = from.obj(read)

  rs.once('close', function () {
    dag.removeListener('add', kick)
  })

  return rs
}
154371
function runMigrations(db, currentVersion) {
  return new Promise((resolve, reject) => {
    const nextVersion = currentVersion + 1;

    if (!migrations[nextVersion]) {
      return resolve();
    }

    if (debug) {
      console.log('Migrating schema to v%d', nextVersion);
    }
    migrations[nextVersion](db)
      .then(() => {
        // write new schemaVersion file
        const json = JSON.stringify({ schemaVersion: nextVersion });
        fs.writeFile(schemaVersionFilePath, json, err => {
          if (err) {
            return reject(err);
          }
          resolve(runMigrations(db, nextVersion));
        });
      })
      .catch(reject);
  });
}
1177662
function iterator (db, opts) {
  if (!iterator.available(db)) {
    throw new Error('level-iterator: this database does not expose iterators')
  }

  // If db exposes iterators, assume they do the decoding
  if (typeof db.iterator === 'function') {
    return db.iterator(opts)
  }

  // If it's a levelup instance, use its codec and iterate the *DOWN db
  const codec = db._codec

  opts = codec.encodeLtgt({
    ...db.options,
    keys: true,
    values: true,
    limit: -1,
    ...( opts || {} )
  })

  opts.keyAsBuffer   = codec.keyAsBuffer(opts)
  opts.valueAsBuffer = codec.valueAsBuffer(opts)

  const iter = db.db.iterator(opts)
  const wrapper = { end: iter.end.bind(iter) }

  wrapper.next = function outerNext (cb) {
    iter.next(function innerNext (err, key, value) {
      if (err) cb(err)
      else if (key === undefined && value === undefined) cb()
      else {
        key = opts.keys ? codec.decodeKey(key, opts) : null
        value = opts.values ? codec.decodeValue(value, opts) : null

        cb(null, key, value)
      }
    })
  }

  if (typeof iter.seek === 'function') {
    wrapper.seek = function outerSeek (target) {
      iter.seek(codec.encodeKey(target, opts))
    }
  } else {
    wrapper.seek = seekNotSupported
  }

  return wrapper
}
244967
def create_db():
    "  "

    from ..ext import db
    db.create_all()

    # Evolution support
    from flask import current_app
    from flaskext.evolution import db as evolution_db
    evolution_db.init_app(current_app)
    evolution_db.create_all()

    print "Database created successfuly"
959571
function read (stream, opts, db, cb) {
  var schema = new exports.Schema;

  if (opts.onType) {
    schema.onType = opts.onType;
  }

  stream.once('error', function (err) {
    debug('aborting with error: ' + err);
    db.close(cb.bind(err));
  });

  stream.on('data', function (doc) {
    var err = schema.consume(doc);
    if (err) return abort(err, stream, db, cb);
  })

  stream.on('end', function () {
    debug('db closing');
    db.close(function () {
      debug('db closed');
      cb(null, schema);
    })
  })
}
804986
function addTableOpt( $opt ) {
		if(isset($this->currentPlatform)) {
			$this->opts[$this->parent->db->databaseType] = $opt;
		}
		return $this->opts;
	}