Get schema for connection
NOTE: Crate DB v1's schema query is not compatible with v0's schema query
In the event v1 query does not work, try v0
If that errors out as well, then let that error bubble up
@param {*} connection
164310
function getSchema(connection) {
  return runQuery(SCHEMA_SQL_V1, connection)
    .then(queryResult => formatSchemaQueryResults(queryResult))
    .catch(() =>
      runQuery(SCHEMA_SQL_V0, connection).then(queryResult =>
        formatSchemaQueryResults(queryResult)
      )
    );
}
768086
function(connection, options){
    if(!connection) throw "Data connection configuration undefined";
    options = options || {};
    this._options = lodash.defaults(options, {
        replication_strategy : {'class' : 'SimpleStrategy', 'replication_factor' : DEFAULT_REPLICATION_FACTOR }
    });
    this._models = {};
    this._keyspace = connection.keyspace;
    this._connection = connection;
    //Compatibility with old parameters name
    if(this._connection.hosts && !this._connection.contactPoints)
        this._connection.contactPoints = this._connection.hosts;
    this._client = null;
}
376904
public static synchronized void getConnection(String poolName, Object mcp, Object cl, Object connection)
   {
      log.tracef("%s", new TraceEvent(poolName,
                                      Integer.toHexString(System.identityHashCode(mcp)),
                                      TraceEvent.GET_CONNECTION,
                                      Integer.toHexString(System.identityHashCode(cl)),
                                      Integer.toHexString(System.identityHashCode(connection))));
   }
409043
def _schema_getter(self, db):
        """"""
        # Change DB connection if needed
        if self.database != db:
            self.change_db(db)
        schema_dict = {tbl: self.get_schema(tbl) for tbl in self.tables}

        schema_lst = []
        for table, schema in schema_dict.items():
            for col in schema:
                col.insert(0, table)
                schema_lst.append(col)
        return schema_lst
43067
function getSchema(connection) {
  connection.maxRows = Number.MAX_SAFE_INTEGER;
  const driver = drivers[connection.driver];
  return driver.getSchema(connection);
}
320008
protected function configureSchema($connection, $config)
    {
        if (isset($config['schema'])) {
            $schema = $this->formatSchema($config['schema']);

            $connection->prepare("set search_path to {$schema}")->execute();
        }
    }
717173
function getConnection(connectionString) {
      return new Promise(function(resolve, reject) {
        // If connectionString is null or undefined, return an error.
        if (_.isEmpty(connectionString)) {
          return reject('getConnection must be called with a mongo connection string');
        }

        // Check if a connection already exists for the provided connectionString.
        var pool = _.findWhere(connections, { connectionString: connectionString });

        // If a connection pool was found, resolve the promise with it.
        if (pool) {
          return resolve(pool.db);
        }

        // If the connection pool has not been instantiated,
        // instantiate it and return the connection.
        MongoClient.connect(connectionString, function(err, database) {
          if (err) {
            return reject(err);
          }

          // Store the connection in the connections array.
          connections.push({
            connectionString: connectionString,
            db: database
          });

          return resolve(database);
        });
      });
    }
1183139
function (connectionInfo, query, params) {
    var connection;

    // Connection validation
    if (typeof connectionInfo.host !== 'string' || connectionInfo.host.length === 0) {
        return respond({
            success: false,
            data: {
                err: 'Bad hostname provided.',
                query: query,
                connection: connectionInfo
            }
        });
    }
    if (typeof connectionInfo.user !== 'string' || connectionInfo.user.length === 0) {
        return respond({
            success: false,
            data: {
                err: 'Bad username provided.',
                query: query,
                connection: connectionInfo
            }
        });
    }

    if (typeof connectionInfo.password !== 'string') {
        return respond({
            success: false,
            data: {
                err: 'Bad password provided.',
                query: query,
                connection: connectionInfo
            }
        });
    }
    if (typeof connectionInfo.database !== 'string' || connectionInfo.database.length === 0) {
        return respond({
            success: false,
            data: {
                err: 'Bad database provided.',
                query: query,
                connection: connectionInfo
            }
        });
    }


    // Return if no sql query specified
    if (query.length === 0) {
        return respond({
            success: false,
            data: {
                err: 'No SQL query specified.'
            }
        });
    }

    // Create the connection to the database
    connection = mysql.createConnection(connectionInfo);

    // Connect to the database
    connection.connect();

    // Do the query
    connection.query(query, params, function (err, rows, fields) {
        // End the connection
        connection.end();

        // Return the error and stop
        if (err) {
            return respond({
                success: false,
                data: {
                    err: err,
                    query: query,
                    connection: connectionInfo
                }

            });
        }

        // Do the callback
        respond({
            success: true,
            data: {
                rows: rows,
                fields: fields
            }
        });
    });
}
374942
function (connection, options) {
	options = options || {};
	var includeKey = options.includeKey;
	
	return map(function (key, callback) {
		connection.get(key, options, includeKey ? function (error, result) {
			if (result != null)
				result.key = key;
			callback(error, result);
		} : callback);
	});
}
429863
function(connection, collection, query, options, cb) {
      return connections[connection].query(query, options, cb);
    }
209391
def get_schema(self, db_alias, entity):
        
        response = self.__app.native_api_call('metaql', 'schema/' + db_alias + '/' + entity, {}, self.__options, False, None, False, http_path="/api/v1/meta/", http_method="GET")
        return json.loads(response.text)
393201
def get(self, event):
        """"""
        self.log("Schemarequest for", event.data, "from",
                 event.user, lvl=debug)
        if event.data in schemastore:
            response = {
                'component': 'hfos.events.schemamanager',
                'action': 'get',
                'data': l10n_schemastore[event.client.language][event.data]
            }
            self.fireEvent(send(event.client.uuid, response))
        else:
            self.log("Unavailable schema requested!", lvl=warn)
447245
protected function createDatabaseSchema(Connection $connection, DatabaseSchemaInterface $schema): void
    {
        try {
            $this->createDatabaseTables($connection, $schema);
            $this->createDatabaseViews($connection, $schema);
        } catch (DBALException $exception) {
            if ($connection->isConnected() === true) {
                $this->removeDatabaseSchema($connection, $schema);
            }

            throw $exception;
        }
    }
1304606
function runQuery(query, connection) {
  const { maxRows } = connection;
  const limit = maxRows < CRATE_LIMIT ? maxRows : CRATE_LIMIT;

  if (connection.port) {
    crate.connect(connection.host, connection.port);
  } else {
    crate.connect(connection.host);
  }

  return crate
    .execute(query)
    .then(res => {
      const results = {
        rows: res.json,
        incomplete: false
      };

      if (results.rows.length >= limit) {
        results.incomplete = true;
        results.rows = results.rows.slice(0, limit);
      }

      return results;
    })
    .catch(err => {
      throw new Error(err.message);
    });
}
744815
function(modelJs) {
    let web = this;
    let modelName = modelJs.name;
    
    if (!modelJs.schema) {
      throw new Error(modelName + '.schema not found.');
    }

    let collectionName = undefined;
    if (modelJs.parentModel) {
      
      let parentModel = web.includeModel(modelJs.parentModel);
      let parentModelJs = parentModel.getModelDictionary();
      collectionName = parentModel.collection.name;

      modelJs.schema = extend(parentModelJs.schema, modelJs.schema);
      
      let origSchema = modelJs.initSchema;
      modelJs.initSchema = [];
      if (origSchema) {
        modelJs.initSchema.push(origSchema);
      }

      if (parentModelJs.initSchema) {
        modelJs.initSchema.push(parentModelJs.initSchema);
      }

      modelJs.options = extend(parentModel.options || {}, modelJs.options);

      if (console.isDebug) {
        console.debug('Model %s has a parent %s', modelName, modelJs.parentModel);
      }

    }

    let conn;

    let getModelConnection = function(modelJs) {
      if (modelJs.connection) {
        return modelJs.connection
      }
      
      if (modelJs.parentModel) {
        return getModelConnection(web.include(modelJs.parentModel));
      }
    }

    let modelConn = getModelConnection(modelJs);
    if (modelConn) {
      conn = this.connections[modelConn];
      if (web.conf.isDebug) {
        console.debug("Found model conn: ", modelJs.name, modelConn);
      }
    } else if (web.connections.mainDb) {
      conn = web.connections.mainDb; 
    } else {
    for (let i in this.connections) {
        //get the first connection
        conn = this.connections[i];
        break;
      }
    }

    if (!conn) {
      console.warn('No defined DB. Check your configuration.');
      return;
    }
    
    let schema = new Schema(modelJs.schema, modelJs.options);

    //TODO: executing schemas of children are not a good idea
    if (modelJs.initSchema) {
      if (modelJs.initSchema instanceof Array) {
        for (let i in modelJs.initSchema) {
          let mySchema = modelJs.initSchema[i];
          
          mySchema(schema);
        }
      } else {
        //console.debug('[%s] Executing normal initSchema %s', modelJs.name ,modelJs.initSchema);
        //fixed bug where schemas are execd twice
        if (!modelJs.initSchema.execd) {
          modelJs.initSchema(schema);
        }
      }
      
    }

    let model = conn.model(modelName, schema, collectionName);
    if (console.isDebug) {
      console.debug("Loaded model for the first time: " + modelName)
    }

    web.modelCache[modelName] = model;
    model.getModelDictionary = function() {
      return modelJs;
    }        
    return model;
  }
734822
public static void createSchema(Connection connection, String dialect, boolean createSchemaMigrations) {
    if (createSchemaMigrations) {
      executeScript(connection, "org/sonar/db/version/schema_migrations-" + dialect + ".ddl");
    }
    executeScript(connection, "org/sonar/db/version/schema-" + dialect + ".ddl");
    executeScript(connection, "org/sonar/db/version/rows-" + dialect + ".sql");
  }
1340460
function setupConnection( options ) {
  var db

  // force this connect option to exist as true
  // http://mongoosejs.com/docs/connections.html#use-mongo-client
  if ( !options.connect.useMongoClient ) {
    options.connect.useMongoClient = true
  }

  // http://mongoosejs.com/docs/promises.html#plugging-in-your-own-promises-library
  mongoose.Promise = global.Promise
  mongoose.set( 'debug', options.debug === true )

  db = mongoose.connection

  if ( options.debug === true ) {
    db.on( 'connected', eventLogger( 'connected', db ) )
    db.on( 'connecting', eventLogger( 'connecting', db ) )
    db.on( 'disconnected', eventLogger( 'disconnected', db ) )
    db.on( 'open', eventLogger( 'open', db ) )
    db.on( 'reconnected', eventLogger( 'reconnected', db ) )
  }

  db.on( 'error', eventLogger( 'error', db ) )
  db.on( 'error', attachErrorToDb( db ) )

  db.uri = getUri( options.uri )

  process.on( 'SIGINT',
    function () {
      mongoose.connection.close(
        function () {
          console.log( 'mongoose default connection disconnected through app termination' )
          process.exit( 0 )
        }
      );
    }
  )

  return db
}