Parse out the database URL from the sails config.

@param sailsConfig Sails config object.
@returns {object} .url and .cleanURL for the database connection.
@throws Error if adapter is not supported.
329768
function parseSailsConfig(sailsConfig) {
  var res = {};
  var connection;

  if (!sailsConfig.migrations) {
    throw new Error('Migrations not configured. Please setup ./config/migrations.js');
  }

  var connectionName = sailsConfig.migrations.connection;
  if (!connectionName) {
    throw new Error('connection missing from ./config/migrations.js');
  }

  connection = sailsConfig.connections[connectionName];

  if (!connection) {
    throw new Error('could not find connection ' + connectionName + ' in ./config/connections.js');
  }

  // build the db url, which contains the password
  res.url = buildURL(connection);
  // check for ssl option in connection config
  if (connection.ssl) {
    res.adapter = connection.adapter;
    res.ssl = true;
  }
  // now build a clean one for logging, without the password
  if (connection.password != null) {
    connection.password = '****';
  }
  res.cleanURL = buildURL(connection);

  return res;
}
192450
function buildConfig (_config) {
  _config.datastore = Object.assign({}, defaultDatastore, _get(_config, 'datastore', {}))

  return _config
}
47616
public function parseConfiguration($config)
    {
        if (is_string($config)) {
            $config = ['url' => $config];
        }

        $url = $config['url'] ?? null;

        $config = Arr::except($config, 'url');

        if (! $url) {
            return $config;
        }

        $parsedUrl = $this->parseUrl($url);

        return array_merge(
            $config,
            $this->getPrimaryOptions($parsedUrl),
            $this->getQueryOptions($parsedUrl)
        );
    }
330289
public static Object jsoupParse(final ChainedHttpConfig config, final FromServer fromServer) {
        try {
            return Jsoup.parse(fromServer.getInputStream(), fromServer.getCharset().name(), fromServer.getUri().toString());
        } catch (IOException e) {
            throw new TransportingException(e);
        }
    }
342365
function MongooseAdapter() {
    this.idAttributeName = cramit.config.database.idAttributeName || '_id';

    if( ! cramit.config.database.instance) {
      //console.log("MongooseAdapter():  Require Mongoose.");
      this.mongoose = require('mongoose');
    } else {
      //console.log("MongooseAdapter():  Using Mongoose instance.");
      this.mongoose = cramit.config.database.instance;
    }
    
    DatabaseAdapter.call(this, cramit.config, cramit.log);
  }
1039096
static private function parseConfig($config){
        if(!empty($config)){
            if(is_string($config)) {
                return self::parseDsn($config);
            }
            $config =   array_change_key_case($config);
            $config = array (
                'type'          =>  $config['db_type'],
                'username'      =>  $config['db_user'],
                'password'      =>  $config['db_pwd'],
                'hostname'      =>  $config['db_host'],
                'hostport'      =>  $config['db_port'],
                'database'      =>  $config['db_name'],
                'dsn'           =>  isset($config['db_dsn'])?$config['db_dsn']:null,
                'params'        =>  isset($config['db_params'])?$config['db_params']:null,
                'charset'       =>  isset($config['db_charset'])?$config['db_charset']:'utf8',
                'deploy'        =>  isset($config['db_deploy_type'])?$config['db_deploy_type']:0,
                'rw_separate'   =>  isset($config['db_rw_separate'])?$config['db_rw_separate']:false,
                'master_num'    =>  isset($config['db_master_num'])?$config['db_master_num']:1,
                'slave_no'      =>  isset($config['db_slave_no'])?$config['db_slave_no']:'',
                'debug'         =>  isset($config['db_debug'])?$config['db_debug']:APP_DEBUG,
                'lite'          =>  isset($config['db_lite'])?$config['db_lite']:false,
            );
        }else {
            $config = array (
                'type'          =>  C('DB_TYPE'),
                'username'      =>  C('DB_USER'),
                'password'      =>  C('DB_PWD'),
                'hostname'      =>  C('DB_HOST'),
                'hostport'      =>  C('DB_PORT'),
                'database'      =>  C('DB_NAME'),
                'dsn'           =>  C('DB_DSN'),
                'params'        =>  C('DB_PARAMS'),
                'charset'       =>  C('DB_CHARSET'),
                'deploy'        =>  C('DB_DEPLOY_TYPE'),
                'rw_separate'   =>  C('DB_RW_SEPARATE'),
                'master_num'    =>  C('DB_MASTER_NUM'),
                'slave_no'      =>  C('DB_SLAVE_NO'),
                'debug'         =>  C('DB_DEBUG',null,APP_DEBUG),
                'lite'          =>  C('DB_LITE'),
            );
        }
        return $config;
    }
982574
function synthesizeUrl(serviceConfig, req, res) {
  const parameters = _.map(serviceConfig.getParameters(req, res), (value, key) => {
    return `${key}=${value}`;
  }).join('&');

  if (parameters) {
    return encodeURI(`${serviceConfig.getUrl(req)}?${parameters}`);
  } else {
    return serviceConfig.getUrl(req);
  }

}
1298659
function (req) {
    var DEFAULT_POPULATE_LIMIT = req._sails.config.blueprints.defaultLimit || 30;
    var aliasFilter = req.param('populate');
    var associations = [];
    var parentModel = req.options.model;

    // Convert the string representation of the filter list to an Array. We
    // need this to provide flexibility in the request param. This way both
    // list string representations are supported:
    //   /model?populate=alias1,alias2,alias3
    //   /model?populate=[alias1,alias2,alias3]
    if (typeof aliasFilter === 'string') {
      aliasFilter = aliasFilter.replace(/\[|\]/g, '');
      aliasFilter = (aliasFilter) ? aliasFilter.split(',') : [];
    }

    _.each(aliasFilter, function(association){
      var childModel = sails.models[association.toLowerCase()];
      // iterate through parent model associations
      _.each(sails.models[parentModel].associations, function(relation){
        // check if association match childModel name
        if(relation.target.name === childModel.name) {
          var obj = { model: childModel, as: relation.options.as };
          if(relation.associationType === 'HasMany') {
            obj.limit = req._sails.config.blueprints.populateLimit || DEFAULT_POPULATE_LIMIT;
          }
          associations.push(obj);
        }
      });
    });

    return associations;
  }
566591
function(config, options) {
      // Make sure config is initialised
      if( ! config ) {
        config = JSON.parse(JSON.stringify(self.defaults));
      }


      var datasetConfig = JSON.parse(JSON.stringify(config));
      var optionsIn = JSON.parse(JSON.stringify(options));
      for (var k in optionsIn) {
        datasetConfig[k] = optionsIn[k];
      }

      return datasetConfig;
    }
1059426
public function parseUrl($config)
    {
        $info = [];

        $info['driver'] = $config['driver'];
        $info['hostname'] = $config['host'];
        $info['port'] = isset($config['port']) ? $config['port'] : '';
        $info['username'] = isset($config['username']) ? $config['username'] : null;
        $info['password'] = isset($config['password']) ? $config['password'] : null;
        $info['database'] = isset($config['database']) ? $config['database'] : null;
        $info['charset'] = (isset($config['charset'])) ? $config['charset'] : '';
        $info['collation'] = (isset($config['collation'])) ? $config['collation'] : '';
        $info['prefix'] = (isset($config['prefix'])) ? $config['prefix'] : '';

        if ($info['hostname'] == 'unix(') {
            $socketDb = null;
            $socketDb = $info['hostname'].'/'.$info['database'];
            if (preg_match_all('/^unix\((.+)\)\/(.+)$/', $socketDb, $matches) > 0) {
                $info['hostname'] = $matches[1][0];
                $info['database'] = $matches[2][0];
            }
        }

        self::setConnectionConfig($info['database'], $info);

        return  $info;
    }
376161
def parse_redis_url(url):
    """"""

    # create config with some sane defaults
    redis_config = {
        "DB": 0,
        "PASSWORD": None,
        "HOST": "localhost",
        "PORT": 6379,
        "SSL": False
    }

    if not url:
        return redis_config

    url = urlparse.urlparse(url)
    # Remove query strings.
    path = url.path[1:]
    path = path.split('?', 2)[0]

    if path:
        redis_config.update({"DB": int(path)})
    if url.password:
        redis_config.update({"PASSWORD": url.password})
    if url.hostname:
        redis_config.update({"HOST": url.hostname})
    if url.port:
        redis_config.update({"PORT": int(url.port)})
    if url.scheme in ['https', 'rediss']:
        redis_config.update({"SSL": True})

    return redis_config
1302687
function convertConfig(jsonConfig) {
  var bunyanConfig = extend({}, jsonConfig);

  if (Array.isArray(bunyanConfig.streams)) {
    bunyanConfig.streams = bunyanConfig.streams.map(convertStream);
  }

  if (bunyanConfig.serializers) {
    bunyanConfig.serializers = convertSerializers(bunyanConfig.serializers);
  }

  return bunyanConfig;
}
777835
function urlConfig (url) {
        var config = {
            path: true,
            query: true,
            hash: true
        };

        if (!url) {
            return config;
        }

        if (RX_PROTOCOL.test(url)) {
            config.protocol = true;
            config.host = true;

            if (RX_PORT.test(url)) {
                config.port = true;
            }

            if (RX_CREDS.test(url)) {
                config.user = true;
                config.pass = true;
            }
        }

        return config;
    }
48692
function (next) {
      var defaultConfig = {
        enabled: true,
        name: "Sails.js",
        type: "_sails._tcp",
        domain: "",
        host: "",
        port: sails.config.proxyPort || sails.config.port
      };

      // Merge default config with custom config.
      config = _.merge(defaultConfig, sails.config.avahi);

      // See if service publishing is desired
      if (!config.enabled) {
        return next();
      }
      // Get the avahi service from dbus.
      service = bus.getService(avahi.DBUS_NAME.value);
      service.getInterface(
        avahi.DBUS_PATH_SERVER.value,
        avahi.DBUS_INTERFACE_SERVER.value,
        function(
          err,
          newServer
        ) {
          server = newServer;
          server.on('StateChanged', stateChanged);
          server.GetState(function(err, state) {
            if (err) {
              sails.log.error('DBus: Could not call org.freedesktop.Avahi.Server.GetState');
              return;
            }
            stateChanged(state);
          });
        }
      );


      return next();
    }
385780
function parseURL(s) {
  var url = null;
  try {
    url = new URL(s);
  } catch (error) {
    console.error(error);
  }
  return url;
}
921548
function parseURL(url) {

	const endpoint = {};

	const purl = urlParser.parse(url, true);

	if (purl.protocol && purl.protocol.startsWith('http')) {
		endpoint.protocol = purl.protocol.slice(0, -1);
		if (purl.hostname) {
			endpoint.hostname = purl.hostname;

			if (purl.port) {
				endpoint.port = parseInt(purl.port);
			}

		} else {
			throw new Error('InvalidURL: missing hostname.');
		}

	} else {
		throw new Error('InvalidURL: url must start with http or https.');
	}

	return endpoint;
}
859602
def parse_database_url(url):
    """"""

    if url == 'sqlite://:memory:':
        # this is a special case, because if we pass this URL into
        # urlparse, urlparse will choke trying to interpret "memory"
        # as a port number
        return {
            'ENGINE': DATABASE_SCHEMES['sqlite'],
            'NAME': ':memory:'
        }
        # note: no other settings are required for sqlite

    # otherwise parse the url as normal
    config = {}

    url = urlparse.urlparse(url)

    # Remove query strings.
    path = url.path[1:]
    path = path.split('?', 2)[0]

    # if we are using sqlite and we have no path, then assume we
    # want an in-memory database (this is the behaviour of sqlalchemy)
    if url.scheme == 'sqlite' and path == '':
        path = ':memory:'

    # Update with environment configuration.
    config.update({
        'NAME': path or '',
        'USER': url.username or '',
        'PASSWORD': url.password or '',
        'HOST': url.hostname or '',
        'PORT': url.port or '',
    })

    if url.scheme in DATABASE_SCHEMES:
        config['ENGINE'] = DATABASE_SCHEMES[url.scheme]

    return config