public
Description: Basic virtual pet game (in the vein of neopets.com) built using the MVC pattern.
Homepage: http://kittokittokitto.yasashiisyndicate.org
Clone URL: git://github.com/OwlManAtt/kittokittokitto.git
Click here to lend your support to: kittokittokitto and make a donation at www.pledgie.com !
kittokittokitto / db / bin / postgres_setsequences.php
100644 65 lines (58 sloc) 1.777 kb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
<?php
/*
* Used post-MySQL import to set the values of the sequences properly.
*
* I ran this from the Kitto root, and it Just Worked. It should reverse-
* engineer all of your tables, find their PK, and set the sequence's current
* value to MAX(pk) with called = true (so it goes +1 when you call nextval).
**/
require_once('includes/config.inc.php');
 
$db = DB::connect($APP_CONFIG['db_dsn']);
if(PEAR::isError($db))
{
    die('Could not connect.');
}
$db->setFetchMode(DB_FETCHMODE_ASSOC);
 
$res = $db->query("
SELECT
pg_class.relname AS tablename,
pg_attribute.attname AS pk_column,
REPLACE(REPLACE(pg_attrdef.adsrc,'nextval(''',''),'''::regclass)','') AS sequence_name
FROM pg_index
INNER JOIN pg_class ON pg_index.indrelid = pg_class.oid
INNER JOIN pg_attribute ON (
pg_class.oid = pg_attribute.attrelid
AND pg_index.indkey[0] = pg_attribute.attnum
)
INNER JOIN pg_attrdef ON (
pg_class.oid = pg_attrdef.adrelid
AND pg_attribute.attnum = pg_attrdef.adnum
)
WHERE indisprimary = true
AND pg_class.relkind = 'r'
");
if(PEAR::isError($res))
{
    die("#1 - {$res->getDebugInfo()}");
}
 
while($res->fetchInto($ROW))
{
    $max = $db->getOne("SELECT MAX(\"{$ROW['pk_column']}\") FROM \"{$ROW['tablename']}\"");
    if(PEAR::isError($max))
    {
        print "Error: {$max->getDebugInfo()}";
        continue;
    }
 
    $max = (int)$max;
    if($max === 0)
    {
        $max = 1;
    }
 
    $reset = $db->query("SELECT setval('{$ROW['sequence_name']}',$max,true)");
    if(PEAR::isError($reset))
    {
        print "Could not set value for {$ROW['sequence_name']}: {$reset->getDebugInfo()}";
    }
}
 
$db->disconnect();
?>