aboutsummaryrefslogtreecommitdiff
path: root/src/sqlop.c
blob: eb3f543aede66574d5d67acf372b8118538123f0 (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
/* This file is part of NSsync 
   Copyright (C) 2011 Sergey Poznyakoff
  
   NSsync is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 3, or (at your option)
   any later version.
  
   NSsync is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.
  
   You should have received a copy of the GNU General Public License
   along with NSsync.  If not, see <http://www.gnu.org/licenses/>. */

#include "nssync.h"

char *sql_config_file;
char *sql_config_group;
char *database_name;
char *sql_host;
char *sql_socket;
char *sql_user;
char *sql_password;
char *sql_cacert;
int sql_port;

MYSQL mysql;

void
sql_connect()
{
	mysql_init(&mysql);

	if (sql_config_file)
		mysql_options(&mysql, MYSQL_READ_DEFAULT_FILE,
			      sql_config_file);
	if (sql_config_group)
		mysql_options(&mysql, MYSQL_READ_DEFAULT_GROUP,
			      sql_config_group);
      
	if (sql_cacert)
		mysql_ssl_set(&mysql, NULL, NULL, sql_cacert, NULL, NULL);
	if (!mysql_real_connect(&mysql, sql_host, sql_user,
				sql_password, database_name, sql_port,
				sql_socket, CLIENT_MULTI_RESULTS)) {
		error("failed to connect to database: %s",
		      mysql_error(&mysql));
		exit(EX_UNAVAILABLE);
	}
	atexit(sql_disconnect);
}

void
sql_disconnect()
{
	mysql_close(&mysql);
}

int
sql_do_query(const char *query, 
	     int (*fun)(MYSQL_ROW, unsigned, void*), void *data)
{
	if (mysql_query(&mysql, query)) {
		error("%s", mysql_error(&mysql));
		error("in query: %s", query);
		return 1;
	}

	do {
		MYSQL_ROW row;
		MYSQL_RES *res;
		unsigned n;
		
		res = mysql_store_result(&mysql);
		if (!res) {
			error("cannot get result: %s", mysql_error(&mysql));
			error("in query: %s", query);
			return 1;
		}

		n = mysql_num_fields(res);
		
		while (row = mysql_fetch_row(res))
			if (fun(row, n, data))
				break;
		mysql_free_result(res);
	} while (mysql_next_result(&mysql) == 0);

	return 0;
}

	

Return to:

Send suggestions and report system problems to the System administrator.