]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/extra/m_sqlv2.h
fbacb99f7446aa9ce6beb14a0f6cd1e52d652a27
[user/henk/code/inspircd.git] / src / modules / extra / m_sqlv2.h
1 #ifndef INSPIRCD_SQLAPI_2
2 #define INSPIRCD_SQLAPI_2
3
4 #include <string>
5 #include <deque>
6 #include <map>
7 #include "modules.h"
8
9 /** SQLreq define.
10  * This is the voodoo magic which lets us pass multiple
11  * parameters to the SQLrequest constructor... voodoo...
12  */
13 #define SQLreq(a, b, c, d, e...) SQLrequest(a, b, c, (SQLquery(d), ##e))
14
15 /** Identifiers used to identify Request types
16  */
17 #define SQLREQID "SQLv2 Request"
18 #define SQLRESID "SQLv2 Result"
19 #define SQLSUCCESS "You shouldn't be reading this (success)"
20
21 /** Defines the error types which SQLerror may be set to
22  */
23 enum SQLerrorNum { NO_ERROR, BAD_DBID, BAD_CONN, QSEND_FAIL, QREPLY_FAIL };
24
25 /** A list of format parameters for an SQLquery object.
26  */
27 typedef std::deque<std::string> ParamL;
28
29 /** The base class of SQL exceptions
30  */
31 class SQLexception : public ModuleException
32 {
33 };
34
35 /** An exception thrown when a bad column or row name or id is requested
36  */
37 class SQLbadColName : public SQLexception
38 {
39 public:
40         SQLbadColName() { }
41 };
42
43 /** SQLerror holds the error state of any SQLrequest or SQLresult.
44  * The error string varies from database software to database software
45  * and should be used to display informational error messages to users.
46  */
47 class SQLerror : public classbase
48 {
49         /** The error id
50          */
51         SQLerrorNum id;
52         /** The error string
53          */
54         std::string str;
55 public:
56         /** Initialize an SQLerror
57          * @param i The error ID to set
58          * @param s The (optional) error string to set
59          */
60         SQLerror(SQLerrorNum i = NO_ERROR, const std::string &s = "")
61         : id(i), str(s)
62         {       
63         }
64         
65         /** Return the ID of the error
66          */
67         SQLerrorNum Id()
68         {
69                 return id;
70         }
71         
72         /** Set the ID of an error
73          * @param i The new error ID to set
74          * @return the ID which was set
75          */
76         SQLerrorNum Id(SQLerrorNum i)
77         {
78                 id = i;
79                 return id;
80         }
81         
82         /** Set the error string for an error
83          * @param s The new error string to set
84          */
85         void Str(const std::string &s)
86         {
87                 str = s;
88         }
89         
90         /** Return the error string for an error
91          */
92         const char* Str()
93         {
94                 if(str.length())
95                         return str.c_str();
96                 
97                 switch(id)
98                 {
99                         case NO_ERROR:
100                                 return "No error";
101                         case BAD_DBID:
102                                 return "Invalid database ID";
103                         case BAD_CONN:
104                                 return "Invalid connection";
105                         case QSEND_FAIL:
106                                 return "Sending query failed";
107                         case QREPLY_FAIL:
108                                 return "Getting query result failed";
109                         default:
110                                 return "Unknown error";                         
111                 }
112         }
113 };
114
115 /** SQLquery provides a way to represent a query string, and its parameters in a type-safe way.
116  * C++ has no native type-safe way of having a variable number of arguments to a function,
117  * the workaround for this isn't easy to describe simply, but in a nutshell what's really
118  * happening when - from the above example - you do this:
119  *
120  * SQLrequest foo = SQLreq(this, target, "databaseid", "SELECT (foo, bar) FROM rawr WHERE foo = '?' AND bar = ?", "Hello", "42");
121  *
122  * what's actually happening is functionally this:
123  *
124  * SQLrequest foo = SQLreq(this, target, "databaseid", query("SELECT (foo, bar) FROM rawr WHERE foo = '?' AND bar = ?").addparam("Hello").addparam("42"));
125  *
126  * with 'query()' returning a reference to an object with a 'addparam()' member function which
127  * in turn returns a reference to that object. There are actually four ways you can create a
128  * SQLrequest..all have their disadvantages and advantages. In the real implementations the
129  * 'query()' function is replaced by the constructor of another class 'SQLquery' which holds
130  * the query string and a ParamL (std::deque<std::string>) of query parameters.
131  * This is essentially the same as the above example except 'addparam()' is replaced by operator,(). The full syntax for this method is:
132  *
133  * SQLrequest foo = SQLrequest(this, target, "databaseid", (SQLquery("SELECT.. ?"), parameter, parameter));
134  */
135 class SQLquery
136 {
137 public:
138         /** The query 'format string'
139          */
140         std::string q;
141         /** The query parameter list
142          * There should be one parameter for every ? character
143          * within the format string shown above.
144          */
145         ParamL p;
146
147         /** Initialize an SQLquery with a given format string only
148          */
149         SQLquery(const std::string &query)
150         : q(query)
151         {
152                 log(DEBUG, "SQLquery constructor: %s", q.c_str());
153         }
154
155         /** Initialize an SQLquery with a format string and parameters.
156          * If you provide parameters, you must initialize the list yourself
157          * if you choose to do it via this method, using std::deque::push_back().
158          */
159         SQLquery(const std::string &query, const ParamL &params)
160         : q(query), p(params)
161         {
162                 log(DEBUG, "SQLquery constructor with %d params: %s", p.size(), q.c_str());
163         }       
164         
165         /** An overloaded operator for pushing parameters onto the parameter list
166          */
167         SQLquery& operator,(const std::string &foo)
168         {
169                 p.push_back(foo);
170                 return *this;
171         }
172         
173         /** An overloaded operator for pushing parameters onto the parameter list.
174          * This has higher precedence than 'operator,' and can save on parenthesis.
175          */
176         SQLquery& operator%(const std::string &foo)
177         {
178                 p.push_back(foo);
179                 return *this;
180         }
181 };
182
183 /** SQLrequest is sent to the SQL API to command it to run a query and return the result.
184  * You must instantiate this object with a valid SQLquery object and its parameters, then
185  * send it using its Send() method to the module providing the 'SQL' feature. To find this
186  * module, use Server::FindFeature().
187  */
188 class SQLrequest : public Request
189 {
190 public:
191         /** The fully parsed and expanded query string
192          * This is initialized from the SQLquery parameter given in the constructor.
193          */
194         SQLquery query;
195         /** The database ID to apply the request to
196          */
197         std::string dbid;
198         /** True if this is a priority query.
199          * Priority queries may 'queue jump' in the request queue.
200          */
201         bool pri;
202         /** The query ID, assigned by the SQL api.
203          * After your request is processed, this will
204          * be initialized for you by the API to a valid request ID,
205          * except in the case of an error.
206          */
207         unsigned long id;
208         /** If an error occured, error.id will be any other value than NO_ERROR.
209          */
210         SQLerror error;
211         
212         /** Initialize an SQLrequest.
213          * For example:
214          *
215          * SQLrequest req = SQLreq(MyMod, SQLModule, dbid, "INSERT INTO ircd_log_actors VALUES('','?')", nick);
216          *
217          * @param s A pointer to the sending module, where the result should be routed
218          * @param d A pointer to the receiving module, identified as implementing the 'SQL' feature
219          * @param databaseid The database ID to perform the query on. This must match a valid
220          * database ID from the configuration of the SQL module.
221          * @param q A properly initialized SQLquery object.
222          */
223         SQLrequest(Module* s, Module* d, const std::string &databaseid, const SQLquery &q)
224         : Request(s, d, SQLREQID), query(q), dbid(databaseid), pri(false), id(0)
225         {
226         }
227         
228         /** Set the priority of a request.
229          */
230         void Priority(bool p = true)
231         {
232                 pri = p;
233         }
234         
235         /** Set the source of a request. You should not need to use this method.
236          */
237         void SetSource(Module* mod)
238         {
239                 source = mod;
240         }
241 };
242
243 /**
244  * This class contains a field's data plus a way to determine if the field
245  * is NULL or not without having to mess around with NULL pointers.
246  */
247 class SQLfield
248 {
249 public:
250         /**
251          * The data itself
252          */
253         std::string d;
254
255         /**
256          * If the field was null
257          */
258         bool null;
259
260         /** Initialize an SQLfield
261          */
262         SQLfield(const std::string &data = "", bool n = false)
263         : d(data), null(n)
264         {
265                 
266         }
267 };
268
269 /** A list of items which make up a row of a result or table (tuple)
270  * This does not include field names.
271  */
272 typedef std::vector<SQLfield> SQLfieldList;
273 /** A list of items which make up a row of a result or table (tuple)
274  * This also includes the field names.
275  */
276 typedef std::map<std::string, SQLfield> SQLfieldMap;
277
278 /** SQLresult is a reply to a previous query.
279  * If you send a query to the SQL api, the response will arrive at your
280  * OnRequest method of your module at some later time, depending on the
281  * congestion of the SQL server and complexity of the query. The ID of
282  * this result will match the ID assigned to your original request.
283  * SQLresult contains its own internal cursor (row counter) which is
284  * incremented with each method call which retrieves a single row.
285  */
286 class SQLresult : public Request
287 {
288 public:
289         /** The original query string passed initially to the SQL API
290          */
291         std::string query;
292         /** The database ID the query was executed on
293          */
294         std::string dbid;
295         /**
296          * The error (if any) which occured.
297          * If an error occured the value of error.id will be any
298          * other value than NO_ERROR.
299          */
300         SQLerror error; 
301         /**
302          * This will match  query ID you were given when sending
303          * the request at an earlier time.
304          */
305         unsigned long id;
306
307         /** Used by the SQL API to instantiate an SQLrequest
308          */
309         SQLresult(Module* s, Module* d, unsigned long i)
310         : Request(s, d, SQLRESID), id(i)
311         {
312         }
313         
314         /**
315          * Return the number of rows in the result
316          * Note that if you have perfomed an INSERT
317          * or UPDATE query or other query which will
318          * not return rows, this will return the
319          * number of affected rows, and SQLresult::Cols()
320          * will contain 0. In this case you SHOULD NEVER
321          * access any of the result set rows, as there arent any!
322          * @returns Number of rows in the result set.
323          */
324         virtual int Rows() = 0;
325         
326         /**
327          * Return the number of columns in the result.
328          * If you performed an UPDATE or INSERT which
329          * does not return a dataset, this value will
330          * be 0.
331          * @returns Number of columns in the result set.
332          */
333         virtual int Cols() = 0;
334         
335         /**
336          * Get a string name of the column by an index number
337          * @param column The id number of a column
338          * @returns The column name associated with the given ID
339          */
340         virtual std::string ColName(int column) = 0;
341         
342         /**
343          * Get an index number for a column from a string name.
344          * An exception of type SQLbadColName will be thrown if
345          * the name given is invalid.
346          * @param column The column name to get the ID of
347          * @returns The ID number of the column provided
348          */
349         virtual int ColNum(const std::string &column) = 0;
350         
351         /**
352          * Get a string value in a given row and column
353          * This does not effect the internal cursor.
354          * @returns The value stored at [row,column] in the table
355          */
356         virtual SQLfield GetValue(int row, int column) = 0;
357         
358         /**
359          * Return a list of values in a row, this should
360          * increment an internal counter so you can repeatedly
361          * call it until it returns an empty vector.
362          * This returns a reference to an internal object,
363          * the same object is used for all calls to this function
364          * and therefore the return value is only valid until
365          * you call this function again. It is also invalid if
366          * the SQLresult object is destroyed.
367          * The internal cursor (row counter) is incremented by one.
368          * @returns A reference to the current row's SQLfieldList
369          */
370         virtual SQLfieldList& GetRow() = 0;
371         
372         /**
373          * As above, but return a map indexed by key name.
374          * The internal cursor (row counter) is incremented by one.
375          * @returns A reference to the current row's SQLfieldMap
376          */
377         virtual SQLfieldMap& GetRowMap() = 0;
378         
379         /**
380          * Like GetRow(), but returns a pointer to a dynamically
381          * allocated object which must be explicitly freed. For
382          * portability reasons this must be freed with SQLresult::Free()
383          * The internal cursor (row counter) is incremented by one.
384          * @returns A newly-allocated SQLfieldList
385          */
386         virtual SQLfieldList* GetRowPtr() = 0;
387         
388         /**
389          * As above, but return a map indexed by key name
390          * The internal cursor (row counter) is incremented by one.
391          * @returns A newly-allocated SQLfieldMap
392          */
393         virtual SQLfieldMap* GetRowMapPtr() = 0;
394         
395         /**
396          * Overloaded function for freeing the lists and maps
397          * returned by GetRowPtr or GetRowMapPtr.
398          * @param fm The SQLfieldMap to free
399          */
400         virtual void Free(SQLfieldMap* fm) = 0;
401
402         /**
403          * Overloaded function for freeing the lists and maps
404          * returned by GetRowPtr or GetRowMapPtr.
405          * @param fl The SQLfieldList to free
406          */
407         virtual void Free(SQLfieldList* fl) = 0;
408 };
409
410 #endif