初始化连接池对象,默认会使用config的database作为key映射pool，
如果传入了dbName且dbName和database不相等，也会使用dbName作为key映射pool，
此时dbName与database指向的是同一个pool
@param {Object} otherConfig
@param {Function} otherConfig.sqlWatcher
497883
function initPool(dbConfig, alias, customizeConfig) {
  if (!alias) alias = DEFAULT_DB_NAME;
  if (!customizeConfig) customizeConfig = {};

  var initialedPool = dbName_pool_[alias];
  if (!initialedPool) {
    var pool = new pg.Pool(dbConfig);
    var dbName = dbConfig.database;
    dbNameList.push(dbName);
    pool.__db__ = dbName;
    dbName_pool_[alias] = pool;
    dbName_pool_[dbName] = pool;

    var startupConfig = { dbConfig, alias, customizeConfig };
    dbName_config_[alias] = startupConfig;
    dbName_config_[dbName] = startupConfig;
  } else {
    if (initialedPool.__db__ != dbConfig.database) {//不允许用一个别名初始化多个不同的数据库
      throw new Error(`alias [${alias}] has already been initialized to db ${initialedPool.__db__}`);
    } else {
      // do nothing, 保证只初始化一次
    }
  }
}
772770
function (connectionName, callback) {
        var self = this,
            _db = Transaction.databases[connectionName],
            transactionId;

        // validate db setup prior to every connection. this ensures nothing goes forward post teardown
        if (!_db) {
            callback(new AdapterError(AdapterError.TRANSACTION_NOT_SETUP));
        }

        // validate connection name
        if (!connectionName) {
            callback(new AdapterError(AdapterError.TRANSACTION_NOT_IDENTIFIED));
        }

        // if this transaction is already connected, then continue
        if (self.connection()) {
            // @todo implement error check when multi-db conn is attempted
            // // callback with error if connection name and current connection mismatch
            // if (connectionName !== self.connection().identity) {
            //     callback(new AdapterError(AdapterError.TRANSACTION_MULTI_DB_CONNECTION_ATTEMPTED));
            // }
            callback(undefined, self.connection());
            return;
        }

        // at this point, it seems like the connection has not been setup yet, so we setup one and then move forward
        transactionId = self.id(); // this will return and cache a new transaction ID if not already present

        // set the actual connection name
        self._connectionName = connectionName;

        _db.getConnection(function (error, conn) {
            if (!error) {
                self._connection = conn; // save reference
                Transaction.associateConnection(conn, transactionId, _db.transactionConfig); // @note disassociate on dc
            }

            callback(error, self._connection);
        });
    }
1114935
function SessionManager(config) {
      this.start = __bind(this.start, this);
      this.storeKey = __bind(this.storeKey, this);
      this.config = extend(this.defaults.config, config);
      this.RedisClient = redis.createClient(config.redis.port, config.redis.host, config.redis);
    }
1171472
public void updateParametersFrom(SQLiteDatabaseConfiguration other) {
        if (other == null) {
            throw new IllegalArgumentException("other must not be null.");
        }
        if (!path.equals(other.path)) {
            throw new IllegalArgumentException("other configuration must refer to "
                    + "the same database.");
        }

        openFlags = other.openFlags;
        maxSqlCacheSize = other.maxSqlCacheSize;
        locale = other.locale;
        foreignKeyConstraintsEnabled = other.foreignKeyConstraintsEnabled;
        customFunctions.clear();
        customFunctions.addAll(other.customFunctions);
    }
330123
function DocumentDBDatabase(config) {
        // Store node for further use
        node = this;
        var nodeConfig = config;

        // Create the Node-RED node
        RED.nodes.createNode(this, config);
        dbendpoint = node.credentials.endpoint;
        dbkey = node.credentials.authkey;

        this.on('input', function (msg) {
            client = new DocumentDBClient(dbendpoint, { "masterKey": dbkey });
            var messageJSON = null;
            if (typeof (msg.payload) != "string") {
                node.log("JSON");
                messageJSON = msg.payload;
            } else {
                node.log("String");
                //Converting string to JSON Object
                //Sample string: {"dbname": "name", "action": "C"}
                messageJSON = JSON.parse(msg.payload);
            }
            var action = messageJSON.action;
            if  (action != "L")
            {
                dbName = messageJSON.dbname;
                databaseUrl = `dbs/${dbName}`;
            }
            // Sending action to Azure DocumentDB
            setStatus(statusEnum.sending);
            switch (action) {
                case "C":
                    node.log('Trying to create database');
                    getDatabase().then((resolve) => { 
                        node.log('Completed successfully: -> ' + JSON.stringify(resolve));
                        setStatus(statusEnum.sent);
                        node.send(messageJSON.dbname); 
                    }).catch((error) => { 
                        setStatus(statusEnum.error);
                        node.error('Completed with error ' +JSON.stringify(error), msg);
                        node.log('Completed with error ' +JSON.stringify(error));
                    });
                    break;
                case "L":
                    node.log('Trying to list databases');
                    var listNames = [];
                    listDatabases(function (dbs) {
                        setStatus(statusEnum.sent);
                        if (dbs.length == 1) {
                            node.send(dbs[0].id)
                        } else {
                            for (var i = 0; i < dbs.length; i++) {
                                listNames.push(dbs[i].id);
                            }
                            node.send(JSON.stringify(listNames));
                        }
                    });
                    break;
                case "D":
                    node.log('Trying to delete database');
                    deleteDatabase().then((resolve) => { 
                        setStatus(statusEnum.sent);
                        node.log('Delete successfully: -> ' + JSON.stringify(resolve));
                     }).catch((error) => { 
                        setStatus(statusEnum.error);
                        node.error('Completed with error ' +JSON.stringify(error), msg);
                        node.log('Completed with error ' +JSON.stringify(error));
                    });
                    break;
                default:
                    node.log('action was not detected');
                    node.error('action was not detected', msg);
                    setStatus(statusEnum.error);
                    break;
            }
        });

        this.on('close', function () {
            disconnectFrom(this);
        });
    }
1235838
function MongoStorage(config) {
  
   var self = this;
   
   this.events = new EventEmitter();
   
   config = protos.extend({
     host: 'localhost',
     port: 27017,
     database: 'store',
     collection: 'keyvalue',
     username: '',
     password: '',
     safe: true
   }, config);
   
   if (typeof config.port != 'number') config.port = parseInt(config.port, 10);
   
   this.config = config;
   
   this.className = this.constructor.name;
   
   app.debug(util.format('Initializing MongoStorage for %s@%s:%s', config.username, config.host, config.port));
   
   var reportError = function(err) {
     app.log(util.format("MongoStore [%s:%s] %s", config.host, config.port, err.code));
     self.client = err;
   }
   
   // Set db
   self.db = new Db(config.database, new Server(config.host, config.port, {}), {safe: config.safe});

   // Add async task
   app.addReadyTask();

   // Get client
   self.db.open(function(err, client) {
     
     if (err) {
       reportError(err);
     } else {
       // Set client
       self.client = client;

       // Get collection
       client.collection(config.collection, function(err, collection) {

         // Set collection
         self.collection = collection;
         
         // Authenticate
         if (config.username && config.password) {

           self.db.authenticate(config.username, config.password, function(err, success) {
             
             if (err) {
               
               app.log(util.format('MongoStorage: unable to authenticate %s@%s', config.username, config.host));
               throw err;
               
             } else {
               
                // Emit initialization event
                self.events.emit('init', self.db, self.client);

             }
           });

         } else {
           
           // Emit initialization event
           self.events.emit('init', self.db, self.client);
           
         }

       });

     }
   });
   
   // Flush async task
   this.events.on('init', function() {
     app.flushReadyTask();
   });
   
   // Set enumerable properties
   protos.util.onlySetEnumerable(this, ['className', 'db']);
}
155055
function MysqlVault(name, logger) {
	var that = this;

	// required exposed properties

	this.name = name;                  // the unique vault name
	this.archive = new Archive(this);  // archivist bindings

	// internals

	this.mysql = null;                 // node-mysql library
	this.config = null;                   // the URI that connections will be established to
	this.pool = null;                  // node-mysql connection pool
	this.logger = logger;

	/* jshint camelcase:false */
	// connection is here for backward compat, please use pool from now on
	this.__defineGetter__('connection', function () {
		logger.debug('Accessing the "connection" property on the mysql vault is deprecated, please' +
			' use the "pool" property');
		return that.pool;
	});
}
1001402
function CouchDB(config, nano) {
	if (!config) {
		throw new Error("Expected a CouchDB configuration");
	}

	if (!config.url) {
		throw new Error("Expected a url in the CouchDB configuration");
	}
	if (!config.database) {
		throw new Error("Expected a database name in the CouchDB configuration");
	}
	if (!config.design) {
		throw new Error("Expected a design document name in the CouchDB configuration");
	}
	if (!config.view) {
		throw new Error("Expected a view name in the CouchDB configuration");
	}
	if (!/\/$/.test(config.url)) {
		config.url += "/";
	}

	this.url = config.url;
	this.database = config.database;
	this.design = config.design;
	this.view = config.view;
	this.name = config.name;
	this.type = "CouchDB Provider";
	this.config = config;

	this.__nano = nano || _nano;
	this.__provider = config.provider || this.__nano(this.url).db.use(this.database);
}
9015
function(name, config)
{
    this.mongo    = require('mongodb');
    this.mongoose = require('mongoose');

    this.config = config;
    this.name   = name;

    this.connection = undefined;
    this.orm        = {
        instance : undefined,
        models   : {}
    };
}
369041
def setup(self, app):
        '''
        
        '''
        for other in app.plugins:
            if not isinstance(other, MySQLPlugin):
                continue
            if other.keyword == self.keyword:
                raise PluginError("Found another mysql plugin with conflicting settings (non-unique keyword).")
            elif other.name == self.name:
                self.name += '_%s' % self.keyword
28405
function (dbName, sql) {
  EventEmitter.apply(this, arguments); // apply parent constructor

  this._addSqlErrorListener(); // register error handler before any SQL is executed

  this._dbName = dbName;
  this._sql = sql ? sql : new SQL(); // TODO: remove new SQL() as sql should always be injected
  this._registerDisconnectListener();

  this._globals = new Globals(this._sql);
  this._roles = new Roles(this._sql, this);
  this._userRoles = new UserRoles(this._sql);
  this._users = new Users(this._sql, this._roles, this._userRoles, this);
  this._colRoles = new ColRoles(this._sql);
  this._policy = new Policy(this._sql, this._roles, this._colRoles, this._userRoles);
  this._cols = new Cols(this._sql, this._policy);
  // this._sessions = new Sessions(this._sql, this._users);

  this._initPartitions();

  this._archive = new Archive(this._partitions, this._globals);
  this._attrs = new Attrs(this._partitions, this._policy, this._users, this._roles, this);
  this._docs = new Docs(this._partitions, this._attrs, this._policy, this._cols);
  this._attrs._docs = this._docs;
  this._queueAttrRecs = new QueueAttrRecs(this._sql);
  this._queue = new Queue(this._sql);
  this._process = new Process(this._sql, this._docs, this._users, this._queueAttrRecs,
    this._partitions, this._cols, this._policy, this._roles,
    this._userRoles, this._attrs, this);
  this._changes = new Changes(this._sql, this._globals, this._users);

  this._models = [this._globals, this._cols, this._users, this._roles, this._userRoles,
    this._colRoles, this._queueAttrRecs
    // this._sessions
  ];
}
75883
function(callback)
    {
        self.pool = (require('mysql')).createPool({
            user     : self.config.username,
            password : self.config.password,
            database : self.config.db,
            host     : self.config.host,
            port     : self.config.port
        });

        // Initiate a connection - just to proof configuration
        self.pool.getConnection(function(err, connection) {

            if (err || !connection) {
                callback && callback(err);
                return;
            }

            self.prepare(connection);

            // The connection can be closed immediately
            connection.release();
            return callback && callback(null, self.pool);
        });
    }
685264
private void parseSQLConfig(final Node node, final ConfigSettings config)
	{

		String name, value;
		Node nnode;
		NodeList list = node.getChildNodes();

		int length = list.getLength();
		for (int i = 0; i < length; i++) {
			nnode = list.item(i);

			name = nnode.getNodeName().toUpperCase();
			if (name.equals(KEY_HOST)) {

				value = nnode.getChildNodes().item(0).getNodeValue();
				config.setConfigParameter(ConfigurationKeys.SQL_HOST, value);

			}
			else if (name.equals(KEY_DATABASE)) {

				value = nnode.getChildNodes().item(0).getNodeValue();
				config.setConfigParameter(ConfigurationKeys.SQL_DATABASE, value);

			}
			else if (name.equals(KEY_USER)) {

				value = nnode.getChildNodes().item(0).getNodeValue();
				config.setConfigParameter(ConfigurationKeys.SQL_USERNAME, value);

			}
			else if (name.equals(KEY_PASSWORD)) {

				value = nnode.getChildNodes().item(0).getNodeValue();
				config.setConfigParameter(ConfigurationKeys.SQL_PASSWORD, value);
			}
		}
	}
739269
function (config) {
        this.config = core.extend({
            connection: 'mongodb://localhost/mvcjs',
            options: {}
        }, config);
        this.db = mongoose.connect(this.config.connection, this.config.options);
        logger.info('Mongo.construct:', this.config);
    }
1215235
function watch(keys, database) {

  keys = keys.map(function(k) {
    if(k instanceof Buffer) return k.toString();
    return k;
  })

  //console.dir(keys);

  // watch can be called multiple times
  // with the same keys, prevent listener leaks
  this.unwatch(database);

  database.on('write', this.onWrite);
  this.watched = keys;
}
550114
function initConnectionPool() {

  const setting = {
    host            : process.env.LIGHTMYSQL_HOST,
    port            : process.env.LIGHTMYSQL_PORT,
    user            : process.env.LIGHTMYSQL_USER,
    password        : process.env.LIGHTMYSQL_PASS,
    database        : process.env.APPNAME,
    connectionLimit : 10
  };

  console.log('MySQL name: ' + setting.database);
  console.log('MySQL host: ' + setting.host);
  console.log('MySQL port: ' + setting.port);
  console.log('MySQL user: ' + setting.user);
  console.log('MySQL pool: ' + setting.connectionLimit);

  return mysql.createPool(setting);
}
472282
function notFoundError(key) {
  var error = new Error(`Key not found in database: ${key}`);

  error.name = 'NotFoundError';
  error.key = key;
  return error;
}