1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2008 InspIRCd Development Team
6 * See: http://www.inspircd.org/wiki/index.php/Credits
8 * This program is free but copyrighted software; see
9 * the file COPYING for details.
11 * ---------------------------------------------------
14 #ifndef INSPIRCD_SQLAPI_2
15 #define INSPIRCD_SQLAPI_2
22 /** Identifiers used to identify Request types
24 #define SQLREQID "SQLv2 Request"
25 #define SQLRESID "SQLv2 Result"
26 #define SQLSUCCESS "You shouldn't be reading this (success)"
28 /** Defines the error types which SQLerror may be set to
30 enum SQLerrorNum { NO_ERROR, BAD_DBID, BAD_CONN, QSEND_FAIL, QREPLY_FAIL };
32 /** A list of format parameters for an SQLquery object.
34 typedef std::deque<std::string> ParamL;
36 /** The base class of SQL exceptions
38 class SQLexception : public ModuleException
41 SQLexception(const std::string &reason) : ModuleException(reason)
45 SQLexception() : ModuleException("SQLv2: Undefined exception")
50 /** An exception thrown when a bad column or row name or id is requested
52 class SQLbadColName : public SQLexception
55 SQLbadColName() : SQLexception("SQLv2: Bad column name")
60 /** SQLerror holds the error state of any SQLrequest or SQLresult.
61 * The error string varies from database software to database software
62 * and should be used to display informational error messages to users.
64 class SQLerror : public classbase
73 /** Initialize an SQLerror
74 * @param i The error ID to set
75 * @param s The (optional) error string to set
77 SQLerror(SQLerrorNum i = NO_ERROR, const std::string &s = "")
82 /** Return the ID of the error
89 /** Set the ID of an error
90 * @param i The new error ID to set
91 * @return the ID which was set
93 SQLerrorNum Id(SQLerrorNum i)
99 /** Set the error string for an error
100 * @param s The new error string to set
102 void Str(const std::string &s)
107 /** Return the error string for an error
119 return "Invalid database ID";
121 return "Invalid connection";
123 return "Sending query failed";
125 return "Getting query result failed";
127 return "Unknown error";
132 /** SQLquery provides a way to represent a query string, and its parameters in a type-safe way.
133 * C++ has no native type-safe way of having a variable number of arguments to a function,
134 * the workaround for this isn't easy to describe simply, but in a nutshell what's really
135 * happening when - from the above example - you do this:
137 * SQLrequest foo = SQLrequest(this, target, "databaseid", SQLquery("SELECT (foo, bar) FROM rawr WHERE foo = '?' AND bar = ?", "Hello", "42"));
139 * what's actually happening is functionally this:
141 * SQLrequest foo = SQLrequest(this, target, "databaseid", query("SELECT (foo, bar) FROM rawr WHERE foo = '?' AND bar = ?").addparam("Hello").addparam("42"));
143 * with 'query()' returning a reference to an object with a 'addparam()' member function which
144 * in turn returns a reference to that object. There are actually four ways you can create a
145 * SQLrequest..all have their disadvantages and advantages. In the real implementations the
146 * 'query()' function is replaced by the constructor of another class 'SQLquery' which holds
147 * the query string and a ParamL (std::deque<std::string>) of query parameters.
148 * This is essentially the same as the above example except 'addparam()' is replaced by operator,(). The full syntax for this method is:
150 * SQLrequest foo = SQLrequest(this, target, "databaseid", (SQLquery("SELECT.. ?"), parameter, parameter));
152 class SQLquery : public classbase
155 /** The query 'format string'
158 /** The query parameter list
159 * There should be one parameter for every ? character
160 * within the format string shown above.
164 /** Initialize an SQLquery with a given format string only
166 SQLquery(const std::string &query)
171 /** Initialize an SQLquery with a format string and parameters.
172 * If you provide parameters, you must initialize the list yourself
173 * if you choose to do it via this method, using std::deque::push_back().
175 SQLquery(const std::string &query, const ParamL ¶ms)
176 : q(query), p(params)
180 /** An overloaded operator for pushing parameters onto the parameter list
182 template<typename T> SQLquery& operator,(const T &foo)
184 p.push_back(ConvToStr(foo));
188 /** An overloaded operator for pushing parameters onto the parameter list.
189 * This has higher precedence than 'operator,' and can save on parenthesis.
191 template<typename T> SQLquery& operator%(const T &foo)
193 p.push_back(ConvToStr(foo));
198 /** SQLrequest is sent to the SQL API to command it to run a query and return the result.
199 * You must instantiate this object with a valid SQLquery object and its parameters, then
200 * send it using its Send() method to the module providing the 'SQL' feature. To find this
201 * module, use Server::FindFeature().
203 class SQLrequest : public Request
206 /** The fully parsed and expanded query string
207 * This is initialized from the SQLquery parameter given in the constructor.
210 /** The database ID to apply the request to
213 /** True if this is a priority query.
214 * Priority queries may 'queue jump' in the request queue.
217 /** The query ID, assigned by the SQL api.
218 * After your request is processed, this will
219 * be initialized for you by the API to a valid request ID,
220 * except in the case of an error.
223 /** If an error occured, error.id will be any other value than NO_ERROR.
227 /** Initialize an SQLrequest.
230 * SQLrequest req = SQLrequest(MyMod, SQLModule, dbid, SQLquery("INSERT INTO ircd_log_actors VALUES('','?')" % nick));
232 * @param s A pointer to the sending module, where the result should be routed
233 * @param d A pointer to the receiving module, identified as implementing the 'SQL' feature
234 * @param databaseid The database ID to perform the query on. This must match a valid
235 * database ID from the configuration of the SQL module.
236 * @param q A properly initialized SQLquery object.
238 SQLrequest(Module* s, Module* d, const std::string &databaseid, const SQLquery &q)
239 : Request(s, d, SQLREQID), query(q), dbid(databaseid), pri(false), id(0)
243 /** Set the priority of a request.
245 void Priority(bool p = true)
250 /** Set the source of a request. You should not need to use this method.
252 void SetSource(Module* mod)
259 * This class contains a field's data plus a way to determine if the field
260 * is NULL or not without having to mess around with NULL pointers.
271 * If the field was null
275 /** Initialize an SQLfield
277 SQLfield(const std::string &data = "", bool n = false)
284 /** A list of items which make up a row of a result or table (tuple)
285 * This does not include field names.
287 typedef std::vector<SQLfield> SQLfieldList;
288 /** A list of items which make up a row of a result or table (tuple)
289 * This also includes the field names.
291 typedef std::map<std::string, SQLfield> SQLfieldMap;
293 /** SQLresult is a reply to a previous query.
294 * If you send a query to the SQL api, the response will arrive at your
295 * OnRequest method of your module at some later time, depending on the
296 * congestion of the SQL server and complexity of the query. The ID of
297 * this result will match the ID assigned to your original request.
298 * SQLresult contains its own internal cursor (row counter) which is
299 * incremented with each method call which retrieves a single row.
301 class SQLresult : public Request
304 /** The original query string passed initially to the SQL API
307 /** The database ID the query was executed on
311 * The error (if any) which occured.
312 * If an error occured the value of error.id will be any
313 * other value than NO_ERROR.
317 * This will match query ID you were given when sending
318 * the request at an earlier time.
322 /** Used by the SQL API to instantiate an SQLrequest
324 SQLresult(Module* s, Module* d, unsigned long i)
325 : Request(s, d, SQLRESID), id(i)
330 * Return the number of rows in the result
331 * Note that if you have perfomed an INSERT
332 * or UPDATE query or other query which will
333 * not return rows, this will return the
334 * number of affected rows, and SQLresult::Cols()
335 * will contain 0. In this case you SHOULD NEVER
336 * access any of the result set rows, as there arent any!
337 * @returns Number of rows in the result set.
339 virtual int Rows() = 0;
342 * Return the number of columns in the result.
343 * If you performed an UPDATE or INSERT which
344 * does not return a dataset, this value will
346 * @returns Number of columns in the result set.
348 virtual int Cols() = 0;
351 * Get a string name of the column by an index number
352 * @param column The id number of a column
353 * @returns The column name associated with the given ID
355 virtual std::string ColName(int column) = 0;
358 * Get an index number for a column from a string name.
359 * An exception of type SQLbadColName will be thrown if
360 * the name given is invalid.
361 * @param column The column name to get the ID of
362 * @returns The ID number of the column provided
364 virtual int ColNum(const std::string &column) = 0;
367 * Get a string value in a given row and column
368 * This does not effect the internal cursor.
369 * @returns The value stored at [row,column] in the table
371 virtual SQLfield GetValue(int row, int column) = 0;
374 * Return a list of values in a row, this should
375 * increment an internal counter so you can repeatedly
376 * call it until it returns an empty vector.
377 * This returns a reference to an internal object,
378 * the same object is used for all calls to this function
379 * and therefore the return value is only valid until
380 * you call this function again. It is also invalid if
381 * the SQLresult object is destroyed.
382 * The internal cursor (row counter) is incremented by one.
383 * @returns A reference to the current row's SQLfieldList
385 virtual SQLfieldList& GetRow() = 0;
388 * As above, but return a map indexed by key name.
389 * The internal cursor (row counter) is incremented by one.
390 * @returns A reference to the current row's SQLfieldMap
392 virtual SQLfieldMap& GetRowMap() = 0;
395 * Like GetRow(), but returns a pointer to a dynamically
396 * allocated object which must be explicitly freed. For
397 * portability reasons this must be freed with SQLresult::Free()
398 * The internal cursor (row counter) is incremented by one.
399 * @returns A newly-allocated SQLfieldList
401 virtual SQLfieldList* GetRowPtr() = 0;
404 * As above, but return a map indexed by key name
405 * The internal cursor (row counter) is incremented by one.
406 * @returns A newly-allocated SQLfieldMap
408 virtual SQLfieldMap* GetRowMapPtr() = 0;
411 * Overloaded function for freeing the lists and maps
412 * returned by GetRowPtr or GetRowMapPtr.
413 * @param fm The SQLfieldMap to free
415 virtual void Free(SQLfieldMap* fm) = 0;
418 * Overloaded function for freeing the lists and maps
419 * returned by GetRowPtr or GetRowMapPtr.
420 * @param fl The SQLfieldList to free
422 virtual void Free(SQLfieldList* fl) = 0;
426 /** SQLHost represents a <database> config line and is useful
427 * for storing in a map and iterating on rehash to see which
428 * <database> tags was added/removed/unchanged.
433 std::string id; /* Database handle id */
434 std::string host; /* Database server hostname */
435 std::string ip; /* resolved IP, needed for at least pgsql.so */
436 unsigned int port; /* Database server port */
437 std::string name; /* Database name */
438 std::string user; /* Database username */
439 std::string pass; /* Database password */
440 bool ssl; /* If we should require SSL */
446 SQLhost(const std::string& i, const std::string& h, unsigned int p, const std::string& n, const std::string& u, const std::string& pa, bool s)
447 : id(i), host(h), port(p), name(n), user(u), pass(pa), ssl(s)
451 /** Overload this to return a correct Data source Name (DSN) for
452 * the current SQL module.
454 std::string GetDSN();
457 /** Overload operator== for two SQLhost objects for easy comparison.
459 bool operator== (const SQLhost& l, const SQLhost& r)
461 return (l.id == r.id && l.host == r.host && l.port == r.port && l.name == r.name && l.user == l.user && l.pass == r.pass && l.ssl == r.ssl);
465 /** QueryQueue, a queue of queries waiting to be executed.
466 * This maintains two queues internally, one for 'priority'
467 * queries and one for less important ones. Each queue has
468 * new queries appended to it and ones to execute are popped
469 * off the front. This keeps them flowing round nicely and no
470 * query should ever get 'stuck' for too long. If there are
471 * queries in the priority queue they will be executed first,
472 * 'unimportant' queries will only be executed when the
473 * priority queue is empty.
475 * We store lists of SQLrequest's here, by value as we want to avoid storing
476 * any data allocated inside the client module (in case that module is unloaded
477 * while the query is in progress).
479 * Because we want to work on the current SQLrequest in-situ, we need a way
480 * of accessing the request we are currently processing, QueryQueue::front(),
481 * but that call needs to always return the same request until that request
482 * is removed from the queue, this is what the 'which' variable is. New queries are
483 * always added to the back of one of the two queues, but if when front()
484 * is first called then the priority queue is empty then front() will return
485 * a query from the normal queue, but if a query is then added to the priority
486 * queue then front() must continue to return the front of the *normal* queue
487 * until pop() is called.
490 class QueryQueue : public classbase
493 typedef std::deque<SQLrequest> ReqDeque;
495 ReqDeque priority; /* The priority queue */
496 ReqDeque normal; /* The 'normal' queue */
497 enum { PRI, NOR, NON } which; /* Which queue the currently active element is at the front of */
505 void push(const SQLrequest &q)
508 priority.push_back(q);
515 if((which == PRI) && priority.size())
517 priority.pop_front();
519 else if((which == NOR) && normal.size())
527 /* Silently do nothing if there was no element to pop() */
535 return priority.front();
537 return normal.front();
542 return priority.front();
548 return normal.front();
551 /* This will probably result in a segfault,
552 * but the caller should have checked totalsize()
553 * first so..meh - moron :p
556 return priority.front();
560 std::pair<int, int> size()
562 return std::make_pair(priority.size(), normal.size());
567 return priority.size() + normal.size();
570 void PurgeModule(Module* mod)
572 DoPurgeModule(mod, priority);
573 DoPurgeModule(mod, normal);
577 void DoPurgeModule(Module* mod, ReqDeque& q)
579 for(ReqDeque::iterator iter = q.begin(); iter != q.end(); iter++)
581 if(iter->GetSource() == mod)
583 if(iter->id == front().id)
585 /* It's the currently active query.. :x */
586 iter->SetSource(NULL);
590 /* It hasn't been executed yet..just remove it */
591 iter = q.erase(iter);