summaryrefslogtreecommitdiffstats
path: root/reset/reset.c
blob: b52f5c46d17ba5b36b7464dd916adb36a098cc12 (plain)
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
/*
 * reset.c
 * House of Mozart statistic database reset app (c) 2003 oliver
 *
 * GNU public license *FIXME*
 */

#include "reset.h"
#include <stdio.h>
#include <getopt.h>
#include <time.h>
#include <libpq-fe.h>

int main(int argc, char *argv[]) {
	int i;
	int options;
	int day;
	int month;
	int year;
	PGconn *conn;
	char SQL_query[512];
	PGresult *res;

	day = month = year = 0;
	
	conn = PQsetdbLogin(PGHOST, PGPORT, PGOPTIONS, PGTTY, DBNAME, LOGIN, PWD);

	for(;-1 != (options = getopt(argc, argv, "hdmya"));) {
		if('h' == options) {
			printf(LONGHELP);
		}
		if('d' == options) {
			day = 23;
		}
		if('m' == options) {
			month = 31;
		}
		if('y' == options) {
			year = 1;
		}
		if('a' == options) {
			day = 23;
			month = 31;
		}
	}

	if(CONNECTION_BAD == PQstatus(conn)) {
		fprintf(stderr, "Connection to database '%s' failed.\n %s", DBNAME, PQerrorMessage(conn));
		PQfinish(conn);
		return 1;
	}
	
	if(0 < day) {
		for(i = 0; i <= day; i++) {
			sprintf(SQL_query, "UPDATE counter_day SET \"%0.2d\" = 0;", i);
			res = PQexec(conn, SQL_query);
			
			if((NULL == res) || (PGRES_COMMAND_OK != PQresultStatus(res))) {
				printf("Unable to execute query: %s\n %s\n", SQL_query, PQerrorMessage(conn));
				PQclear(res);
				PQfinish(conn);
				return 1;
			}
			PQclear(res);
		}
	}
	if(0 < month) {
		for(i = 1; i <= month; i++) {
			sprintf(SQL_query, "UPDATE counter_month SET \"%0.2d\" = 0;", i);
			res = PQexec(conn, SQL_query);

			if((NULL == res) || (PGRES_COMMAND_OK != PQresultStatus(res))) {
				printf("Unable to execute query: %s\n %s\n", SQL_query, PQerrorMessage(conn));
				PQclear(res);
				PQfinish(conn);
				return 1;
			}
			PQclear(res);
		}
	}
	if(1 == year) {
		sprintf(SQL_query, "INSERT INTO counter_year VALUES (counter_year.year +1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);");
		res = PQexec(conn, SQL_query);

		if((NULL == res) || (PGRES_COMMAND_OK != PQresultStatus(res))) {
			printf("Unable to execute query: %s\n %s\n", SQL_query, PQerrorMessage(conn));
			PQclear(res);
			PQfinish(conn);
			return 1;
		}
		PQclear(res);
	}
	PQfinish(conn);

	return 0;
}