Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression to parse SQL Structure

I am trying to parse the MySQL data types returned by "DESCRIBE [TABLE]".

It returns strings like:

int(11)
float
varchar(200)
int(11) unsigned
float(6,2)

I've tried to do the job using regular expressions but it's not working.

PHP CODE:

$string = "int(11) numeric";<br/>
$regex = '/(\w+)\s*(\w+)/';<br/>
var_dump( preg_split($regex, $string) );<br/>
like image 378
Miro Avatar asked Dec 29 '22 15:12

Miro


2 Answers

Query the information schema for introspection of tables and columns, and more.

like image 94
Marco Mariani Avatar answered Dec 31 '22 13:12

Marco Mariani


I wrote code to do this in Zend_Db_Adapter_Mysqli::describeTable().
It handles varchar, char, decimal, float, and all MySQL integer types.

I won't post the code here because of StackOverflow's CC-wiki license policy, but go check it out at that link.

mysql_fetch_field() only reports data types for query result sets, not persisted tables.

INFORMATION_SCHEMA is another option, but MySQL's early implementation of it has incredibly poor performance, which makes it hard to use in a web app that needs quick response time. Some changes in MySQL 5.1.23 tried to improve the performance, but some people still report problems.

like image 35
Bill Karwin Avatar answered Dec 31 '22 12:12

Bill Karwin