Diagnose database and tables, this function is used
to verify database and driver settings, db engine types, etc.

@return string null means everything ok, string means problem found.
320780
public function diagnose() {
        // Verify the database is running with READ_COMMITTED_SNAPSHOT enabled.
        // (that's required to get snapshots/row versioning on READ_COMMITED mode).
        $correctrcsmode = false;
        $sql = "SELECT is_read_committed_snapshot_on
                  FROM sys.databases
                 WHERE name = '{$this->dbname}'";
        $this->query_start($sql, null, SQL_QUERY_AUX);
        $result = sqlsrv_query($this->sqlsrv, $sql);
        $this->query_end($result);
        if ($result) {
            if ($row = sqlsrv_fetch_array($result)) {
                $correctrcsmode = (bool)reset($row);
            }
        }
        $this->free_result($result);

        if (!$correctrcsmode) {
            return get_string('mssqlrcsmodemissing', 'error');
        }

        // Arrived here, all right.
        return null;
    }
394651
private function check_errors() {
 	 	switch($this->db['phptype']) {
 	 		case "sqlite":
				if ($this->sqlite_version == 3) {
					$this->errno = $this->conn->lastErrorCode();
					$this->error = $this->conn->lastErrorMsg();
				} else {
					$this->errno = sqlite_last_error($this->conn);
					$this->error = sqlite_error_string($this->errno);
				}
 	 			break;
 	 		case "mysql":
 	 			$this->errno = mysql_errno($this->conn);
 	 			$this->error = mysql_error($this->conn);
 	 			break;
 	 		case "mysqli":
				if (mysqli_connect_error()) {
					die('Connect Error: ' . mysqli_connect_error());
				}
 	 			$this->errno = mysqli_errno($this->conn);
 	 			$this->error = mysqli_error($this->conn);
 	 			break;
 	 	}

 	}
322927
public function check()
	{
		// Check if the db connector has been set.
		if (!($this->db instanceof MysqlDriver))
		{
			throw new \Exception('Database connection wrong type.');
		}

		// Check if the tables have been specified.
		if (empty($this->from))
		{
			throw new \Exception('ERROR: No Tables Specified');
		}

		return $this;
	}
1256509
public static function getPDODriver() {
        if (!class_exists('PDO')) {
            return null;
        }
        foreach(PDO::getAvailableDrivers() as $driver) {
            if(in_array($driver, array('sqlsrv', 'dblib'))) {
                return $driver;
            }
        }
        return null;
    }
33039
private static function _get_databases(): ?databases
  {
    if ( self::check() ){
      if ( !self::$databases_obj && ($db = self::_get_db()) ){
        self::$databases_obj = new databases($db);
      }
      return self::$databases_obj;
    }
    return null;
  }
1251783
public function check_database()
    {

        $this->line(' * Checking Database');
        $this->table(['Setting', 'Value'], [
            ['Connection', env('DB_CONNECTION')],
            ['Host', env('DB_HOST')],
            ['Database', env('DB_DATABASE')],
            ['Username', env('DB_USERNAME')],
            ['Password', str_repeat('*', strlen(env('DB_PASSWORD')))],
        ]);

        try {

            $this->info('Connection OK to database: ' .
                DB::connection()->getDatabaseName());

        } catch (Exception $e) {

            $this->error('Unable to connect to database server: ' . $e->getMessage());
        }
    }
1248182
public function getSqlString() {
        $sql = $this->getSQL();
        if ($sql && $this->values) {
            foreach ($this->values as $value) {
                list ($name, $val, $type, , $rkey) = $value;
                if ($this->whereData) {
                    $val = isset($this->whereData[ $rkey ]) ? $this->whereData[ $rkey ] : (isset($this->whereData[ $name ]) ? $this->whereData[ $name ] : $val);
                }
                if ($type == \PDO::PARAM_STR) {
                    $sql = str_replace($name, $this->dialect->quote($val), $sql);
                } else {
                    $sql = str_replace($name, $val, $sql);
                }
            }
        }

        return $sql;
    }
170293
public function getConnectionString()
    {
        $this->parseDsn();
        $connect_parameters = [
            sprintf(
                "user=%s dbname=%s",
                $this->configuration['user'],
                $this->configuration['database']
            )
        ];

        if ($this->configuration['host'] !== '') {
            $connect_parameters[] = sprintf('host=%s', $this->configuration['host']);
        }

        if ($this->configuration['port'] !== '') {
            $connect_parameters[] = sprintf('port=%s', $this->configuration['port']);
        }

        if ($this->configuration['pass'] !== '') {
            $connect_parameters[] = sprintf('password=%s', addslashes($this->configuration['pass']));
        }

        return join(' ', $connect_parameters);
    }
1153570
protected function hasDatabaseInfoChanged()
    {
        $settings_uri = $this->settingLocalFile;
        if (file_exists($settings_uri)) {
            $settings = file_get_contents($settings_uri);
            $match_status = preg_match_all("/\'(database|username|password|host|port|driver)\'\s=>\s\'(.+)\'\,?/", $settings, $matches);

            if ($match_status !== false) {
                $database = $this->getDatabaseInfo();
                $database_file = array_combine($matches[1], $matches[2]);

                foreach ($database->asArray() as $property => $value) {
                    if (isset($database_file[$property])
                        && $database_file[$property] != $value) {
                        return true;
                    }
                }
            }
        }

        return false;
    }
819493
public function validateConditionsTrigger()
    {
        $field = 'data.conditions';

        if ($this->isExcluded($field)) {
            return null;
        }

        $value = $this->getSubmitted($field);

        if ($this->isUpdating() && !isset($value)) {
            $this->unsetSubmitted($field);
            return null;
        }

        $label = $this->translation->text('Conditions');

        if (empty($value)) {
            $this->setErrorRequired($field, $label);
            return false;
        }

        if (!is_array($value)) {
            $this->setErrorInvalid($field, $label);
            return false;
        }

        $submitted = $this->getSubmitted();
        $operators = array_map('htmlspecialchars', array_keys($this->condition->getOperators()));

        $errors = $modified = array();

        foreach ($value as $line => $condition) {

            $line++;

            $parts = gplcart_string_explode_whitespace($condition, 3);
            $condition_id = array_shift($parts);
            $operator = array_shift($parts);
            $parameters = array_filter(explode(',', implode('', $parts)), function ($value) {
                return $value !== '';
            });

            if (empty($parameters)) {
                $errors[] = $line;
                continue;
            }

            if (!in_array(htmlspecialchars($operator), $operators)) {
                $errors[] = $line;
                continue;
            }

            $args = array($parameters, $operator, $condition_id, $submitted);
            $result = $this->validateConditionTrigger($condition_id, $args);

            if ($result !== true) {
                $errors[] = $line;
                continue;
            }

            $modified[] = array(
                'weight' => $line,
                'id' => $condition_id,
                'value' => $parameters,
                'operator' => $operator,
                'original' => "$condition_id $operator " . implode(',', $parameters),
            );
        }

        if (!empty($errors)) {
            $error = $this->translation->text('Error in @num definition', array('@num' => implode(',', $errors)));
            $this->setError($field, $error);
        }

        if ($this->isError()) {
            return false;
        }

        $this->setSubmitted($field, $modified);
        return true;
    }
623184
public static function database_is_ready()
    {
        // Used for unit tests
        if (self::$force_database_is_ready !== null) {
            return self::$force_database_is_ready;
        }

        if (self::$database_is_ready) {
            return self::$database_is_ready;
        }

        $requiredClasses = ClassInfo::dataClassesFor(Member::class);
        $requiredClasses[] = Group::class;
        $requiredClasses[] = Permission::class;
        $schema = DataObject::getSchema();
        foreach ($requiredClasses as $class) {
            // Skip test classes, as not all test classes are scaffolded at once
            if (is_a($class, TestOnly::class, true)) {
                continue;
            }

            // if any of the tables aren't created in the database
            $table = $schema->tableName($class);
            if (!ClassInfo::hasTable($table)) {
                return false;
            }

            // HACK: DataExtensions aren't applied until a class is instantiated for
            // the first time, so create an instance here.
            singleton($class);

            // if any of the tables don't have all fields mapped as table columns
            $dbFields = DB::field_list($table);
            if (!$dbFields) {
                return false;
            }

            $objFields = $schema->databaseFields($class, false);
            $missingFields = array_diff_key($objFields, $dbFields);

            if ($missingFields) {
                return false;
            }
        }
        self::$database_is_ready = true;

        return true;
    }
821949
protected function validateDbConnectInstall()
    {
        if ($this->isError()) {
            return null;
        }

        $field = 'database.connect';

        if ($this->isExcluded($field)) {
            return null;
        }

        $settings = $this->getSubmitted('database');
        $result = $this->install->connectDb($settings);

        if ($result === true) {
            return true;
        }

        if (empty($result)) {
            $result = $this->translation->text('Could not connect to database');
        }

        $this->setError($field, (string) $result);
        return false;
    }
998932
private function checkDB() {
		$res = $this->query('select * from sqlite_master where type=\'table\' and name=\'dropbox\'; ');
		if (! $res) {
			try {
				$this->DB->exec('create table '.$this->DB_TableName.'(path text, fname text, dat blob, isdir integer);');
				$this->DB->exec('create index nameidx on '.$this->DB_TableName.'(path, fname)');
				$this->DB->exec('create index isdiridx on '.$this->DB_TableName.'(isdir)');
			} catch (PDOException $e) {
				return $this->setError($e->getMessage());
			}
		}
		return true;
	}
20873
public function getInfo()
	{
		if ($this->error || !$this->sql) {
			return null;
		}

		$query = 'EXPLAIN FORMAT=JSON ' . $this->sql;
		$query = $this->db->getPdo()->query($query);

		$data = [];
		if ($query) {
			$data = $query->fetch();
		}

		$data = Json::decode($data['EXPLAIN'] ?? '[]');

		return Dumper::toHtml($data, [
			Dumper::COLLAPSE => true,
			Dumper::DEPTH => 6,
		]);
	}
680057
public static function getDbo()
	{
		if (!self::$database)
		{
			//get config values

			$host = Config::get()->get('database.host');
			$user = Config::get()->get('database.user');
			$password = Config::get()->get('database.password');
			$database = Config::get()->get('database.name');
			$prefix = Config::get()->get('database.prefix');
			$driver = Config::get()->get('database.driver');
			$debug = Config::get()->get('database.debug');

			//added extra code to prevent error when $driver is incorrect

			$options = array('driver' => $driver, 'host' => $host, 'user' => $user, 'password' => $password, 'database' => $database, 'prefix' => $prefix);

			self::$database = DatabaseFactory::getInstance()->getDriver($driver, $options);

			//get the debug configuration setting
			self::$database->setDebug(Config::get()->get('debug'));
		}
		return self::$database;
	}
1314810
protected String determineDatabaseType() throws HandlerException {
        String dbName = null;
        try (Connection conn = getConnection()) {
            dbName = conn.getMetaData().getDatabaseProductName();
        } catch (SQLException e) {
            throw new HandlerException("Exception occured while getting DB Name",
                    DatabaseAuditHandler.class, e);
        }
        return dbName;
    }
1332696
public function checkTable()
    {
        return is_string($this->table_name = $this->table_descriptor->getStorageName()) &&
            $this->table_descriptor->hasFields() &&
            $this->checkPrimaryConstraint()
        ;
    }