#!/usr/bin/php -q
<?php

$conn = pg_connect("host=localhost dbname=stats") or die ("couldn't connect to db");
# We assume this partition exists already...
$schema = "partitions";
pg_query("set search_path='partitions','public'");

for ($i=0;$i<30;$i++){
	$day = date('Y-m-d',time()+(86400*$i)); 
	$nextday = date('Y-m-d',time()+(86400*($i+1))); 
	$tabledate = date('Ymd',time()+(86400*$i));
	$tablename = "page_access_".$tabledate; 
	$query = "SELECT count(1) FROM pg_catalog.pg_class c LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace WHERE c.relname ~ '^($tablename)$' AND pg_catalog.pg_table_is_visible(c.oid) and n.nspname='partitions';";
	$res = pg_query($query);
	$count = pg_fetch_assoc($res);
	if ($count['count']==0){
		print "creating partition $tablename \n";
		pg_query("begin");
		pg_query("create table $tablename (check (\"timestamp\" >= '$day 00:00:00' and \"timestamp\" < '$nextday 00:00:00')) inherits (page_access)");
		pg_query ("create unique index ".$tablename."_paid on ".$tablename." (paid)");
		pg_query ("commit");
	}
}
?>