]> git.xonotic.org Git - xonotic/xonstatdb.git/blob - scripts/gen_trigger.shl
Add table definitions.
[xonotic/xonstatdb.git] / scripts / gen_trigger.shl
1 #!/bin/bash
2
3 table=$1
4 start_year=$2
5 end_year=$3
6
7 for year in `seq $start_year $end_year`
8 do
9     for qtr in "q1" "q2" "q3" "q4"
10     do
11         printf "CREATE TABLE IF NOT EXISTS xonstat.%s_%s%s ( \n" $table $year $qtr
12         if [[ $qtr = "q1" ]]
13         then
14             printf "\tCHECK ( create_dt >= DATE '%s-01-01' AND create_dt < DATE '%s-04-01' ) \n" $year $year
15         elif [[ $qtr = "q2" ]]
16         then
17             printf "\tCHECK ( create_dt >= DATE '%s-04-01' AND create_dt < DATE '%s-07-01' ) \n" $year $year
18         elif [[ $qtr = "q3" ]]
19         then
20             printf "\tCHECK ( create_dt >= DATE '%s-07-01' AND create_dt < DATE '%s-10-01' ) \n" $year $year
21         elif [[ $qtr = "q4" ]]
22         then
23             next_year=$[year + 1]
24             printf "\tCHECK ( create_dt >= DATE '%s-10-01' AND create_dt < DATE '%s-01-01' ) \n" $year $next_year
25         fi
26
27         printf ") INHERITS (%s);\n\n" $table
28     done
29 done
30 printf "\n"
31
32 printf "CREATE OR REPLACE FUNCTION %s_ins()\n" $table
33 printf "RETURNS TRIGGER AS \$\$\n"
34 printf "BEGIN\n"
35
36 for i in `seq $start_year $end_year`
37 do
38
39     if [[ start_year -eq i ]]
40     then
41         printf "\tIF (NEW.create_dt >= DATE '%s-01-01' AND NEW.create_dt < DATE '%s-04-01') THEN\n" $i $i
42     else
43         printf "\tELSIF (NEW.create_dt >= DATE '%s-01-01' AND NEW.create_dt < DATE '%s-04-01') THEN\n" $i $i
44     fi
45     printf "\t\tINSERT INTO %s_%sQ1 VALUES (NEW.*);\n" $table $i
46
47     printf "\tELSIF (NEW.create_dt >= DATE '%s-04-01' AND NEW.create_dt < DATE '%s-07-01') THEN\n" $i $i
48     printf "\t\tINSERT INTO %s_%sQ2 VALUES (NEW.*);\n" $table $i
49
50     printf "\tELSIF (NEW.create_dt >= DATE '%s-07-01' AND NEW.create_dt < DATE '%s-10-01') THEN\n" $i $i
51     printf "\t\tINSERT INTO %s_%sQ3 VALUES (NEW.*);\n" $table $i
52
53     next_year=$[i + 1]
54     printf "\tELSIF (NEW.create_dt >= DATE '%s-10-01' AND NEW.create_dt < DATE '%s-01-01') THEN\n" $i $next_year
55     printf "\t\tINSERT INTO %s_%sQ4 VALUES (NEW.*);\n" $table $i
56
57 done
58
59 printf "\tELSE\n"
60 printf "\t\tRAISE EXCEPTION 'Date out of range. Fix the %s_ins() trigger!';\n" $table
61 printf "\tEND IF;\n"
62 printf "\tRETURN NULL;\n"
63
64 printf "END\n"
65 printf "\$\$\n"
66 printf "LANGUAGE plpgsql;\n\n"
67
68 printf "DROP TRIGGER IF EXISTS %s_ins_trg ON xonstat.games;\n" $table
69 printf "CREATE TRIGGER %s_ins_trg\n" $table
70 printf "BEFORE INSERT on xonstat.%s\n" $table
71 printf "FOR EACH ROW EXECUTE PROCEDURE %s_ins();\n" $table