Saturday, November 14, 2009

get basic stats from a table.


$arPgUser = array("user"=> "postgres","host"=>"localhost","dbname"=>"dev","password" => "i1m2a3p4o5o6p7e8r9");
$connStr = getConnStr($arPgUser);
$conn = pg_connect($connStr);
$table = "books";

$sqlGetSchema = "select column_name,data_type from information_schema.columns where table_name = '{$table}'";
$res = pg_fetch_all(pg_query($conn,$sqlGetSchema));
$columns = array_map("sqlFieldStats",($res));

$sqlBuildStats= sqlBuildStats($columns,$table);
$res = pg_fetch_all(pg_query($conn,$sqlBuildStats));
print_r($res);

pg_close($conn);

function sqlBuildStats($columns,$table){

$sqlColumns = implode(",\n",$columns);
$sql = "
select
$sqlColumns
from
$table
";
echo "{$sql}\n";

return trim($sql);
}

function sqlFieldStats($arSchema){

switch($arSchema['data_type']){

case "text":
return "count(distinct({$arSchema['column_name']})) as dist_{$arSchema['column_name']}";
break;

case "numeric":
return "sum({$arSchema['column_name']}) as sum_{$arSchema['column_name']}";
break;
}
}


function getConnStr($arPgUser){

$connStr = "";
foreach ($arPgUser as $key => $value)
$connStr.= "{$key} = {$value} ";

return $connStr;
}

No comments: