php使用元数据,PHP 获得表的元数据

用户评论:

jsnell at e-normous dot com (2007-11-12 15:24:01)

The built in function does not provide any support for selecting a schema. If you need schema support and do not want to alter your SEARCH_PATH, the following function can provide it:

function meta_data($table, $schema = 'public')

{

$result = pg_query_params("SELECT a.attname, a.attnum, t.typname, a.attlen, a.attnotNULL, a.atthasdef, a.attndims

FROM pg_class as c, pg_attribute a, pg_type t, pg_namespace n

WHERE a.attnum > 0

AND a.attrelid = c.oid

AND c.relname = $1

AND a.atttypid = t.oid

AND n.oid = c.relnamespace

AND n.nspname = $2

ORDER BY a.attnum", array($table, $schema));

$fields = array();

while($row = pg_fetch_array()) {

$fields['attname'] = $row;

}

return $fields;

}

yarnofmoo at gmail dot com (2007-06-27 08:32:41)

You can get some possibly more useful information with the query:

SELECT table_name, column_name, data_type, character_maximum_length FROM information_schema.columns WHERE table_name='tablename';

rburghol at vt dot edu (2005-06-24 06:37:01)

When querying on meta data from a temp table, the meta data seems to persist even if a fresh connection is established, where the temp table no longer exists.

For example, if you create a connection and a temp table like so:

$dbconn1 = pg_connect('blah blah', , PGSQL_CONNECT_FORCE_NEW);

pg_exec($dbconn1,'create temp table foo as select 'foo' as namecol, 'bar' as valcol');

Then create a new connection

$dbconn2 = pg_connect('blah blah', , PGSQL_CONNECT_FORCE_NEW);

And query the meta data for table 'foo' in this new connection, it will report the facts about this table:

pg_meta_data($dbconn2,'foo');

"'Array ( [foo] => Array ( [num] => 1 [type] => varchar... "

However, trying to remove this table:

pg_exec($dbconn,'drop table foo');

Throws an error:

pg_exec(): Query failed: ERROR: table "foo" does not exist in ...

dmiller at NOSPAM dot judcom dot nsw dot gov dot au (2003-06-18 01:31:03)

This function seems to be case-sensitive on tablename (php-4.3.1)

The Array returned is of the following structure

['field name'] => Array

(

['num'] => Field number starting at 1

['type'] => data type, eg varchar, int4

['len'] => internal storage size of field. -1 for varying

['not null'] => boolean

['has default'] => boolean

)

......

for Varied size datatypes (varchar, text, etc)

you can get the max data length from the system table pg_attribute.atttypmod -4

eg.

select attnum, attname , atttypmod -4 as field_len

from pg_attribute, pg_class

where relname='$tablename'

and attrelid=relfilenode

and attnum>=1

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值