lithium\data\source\database\adapter\PostgreSql::describe()

public method

Gets the column schema for a given PostgreSQL table.

Parameters

  • mixed $entity

    Specifies the table name for which the schema should be returned, or the class name of the model object requesting the schema, in which case the model class will be queried for the correct table name.

  • array $fields

    Any schema data pre-defined by the model.

  • array $meta

Returns

array

Returns an associative array describing the given table's schema, where the array keys are the available fields, and the values are arrays describing each field, containing the following keys:

  • 'type': The field type name

Filter

This method can be filtered.

Source

	public function describe($entity, $fields = [], array $meta = []) {
		$schema = $this->_config['schema'];
		$params = compact('entity', 'meta', 'fields', 'schema');

		return Filters::run($this, __FUNCTION__, $params, function($params) {
			extract($params);

			if ($fields) {
				return Libraries::instance(null, 'schema', compact('fields'), $this->_classes);
			}
			$name = $this->connection->quote($this->_entityName($entity));
			$schema = $this->connection->quote($schema);

			$sql  = 'SELECT "column_name" AS "field", "data_type" AS "type",	';
			$sql .= '"is_nullable" AS "null", "column_default" AS "default", ';
			$sql .= '"character_maximum_length" AS "char_length" ';
			$sql .= 'FROM "information_schema"."columns" WHERE "table_name" = ' . $name;
			$sql .= ' AND table_schema = ' . $schema . ' ORDER BY "ordinal_position"';

			$columns = $this->connection->query($sql)->fetchAll(PDO::FETCH_ASSOC);
			$fields = [];

			foreach ($columns as $column) {
				$schema = $this->_column($column['type']);
				$default = $column['default'];

				if (preg_match("/^'(.*)'::/", $default, $match)) {
					$default = $match[1];
				} elseif ($default === 'true') {
					$default = true;
				} elseif ($default === 'false') {
					$default = false;
				} else {
					$default = null;
				}
				$fields[$column['field']] = $schema + [
					'null'     => ($column['null'] === 'YES' ? true : false),
					'default'  => $default
				];
				if ($fields[$column['field']]['type'] === 'string') {
					$fields[$column['field']]['length'] = $column['char_length'];
				}
			}
			return Libraries::instance(null, 'schema', compact('fields'), $this->_classes);
		});
	}