List:MySQL++« Previous MessageNext Message »
From:Chris Frey Date:February 9 2005 4:33am
Subject:[patch] BadFieldName exception
View as plain text  
Hello again,

In the interests of code correctness and safety, here is a patch for a new
exception: BadFieldName.  This is only thrown from lookup_by_name if the
name specified was not found.

This isn't strictly necessary if the previous []/at() patch is accepted,
but should help with debugging, and would be extremely useful if field
names come from an external source that the software doesn't control.

Anyway, I post the patch here for comment and analysis. :-)

Enjoy,
- Chris



Index: software/mysql++/lib/exceptions.h.in
diff -u software/mysql++/lib/exceptions.h.in:1.2 software/mysql++/lib/exceptions.h.in:1.3
--- software/mysql++/lib/exceptions.h.in:1.2	Sun Feb  6 23:35:38 2005
+++ software/mysql++/lib/exceptions.h.in	Tue Feb  8 23:29:11 2005
@@ -1,6 +1,7 @@
 #ifndef MYSQLPP_EXCEPTIONS_H
 #define MYSQLPP_EXCEPTIONS_H
 #include <string>
+#include <vector>
 
 namespace mysqlpp {
 
@@ -64,6 +65,21 @@
   virtual const char* what( void ) const throw () { return _what.c_str(); }
 };
 
+//: Exception thrown when lookup_by_name can't find the specified field.
+class BadFieldName : public std::exception {
+  std::string _what;
+public:
+  std::vector<std::string> known_fields;
+public:
+  BadFieldName(const char *bad_field, const std::vector<std::string> &names)
+    : known_fields(names) {
+      _what = "Unknown field name: ";
+      _what += bad_field;
+    }
+  ~BadFieldName() throw() {}
+  virtual const char* what( void ) const throw () { return _what.c_str(); }
+};
+
 #else //original, default exception style
 
 struct BadQuery {
@@ -97,6 +113,18 @@
   const char* error; //:
 };
 
+
+//: Exception thrown when lookup_by_name can't find the specified field.
+class BadFieldName {
+public:
+  std::string bad_field;
+  std::vector<std::string> known_fields;
+
+  BadFieldName(const char *bad, const std::vector<std::string> &names)
+    : bad_field(bad), known_fields(names) {}
+};
+
+
 #endif
 
 } // end namespace mysqlpp
Index: software/mysql++/lib/row.cpp
diff -u software/mysql++/lib/row.cpp:1.2 software/mysql++/lib/row.cpp:1.3
--- software/mysql++/lib/row.cpp:1.2	Fri Feb  4 23:03:10 2005
+++ software/mysql++/lib/row.cpp	Tue Feb  8 23:29:11 2005
@@ -1,6 +1,6 @@
 #include "row.h"
-
 #include "result.h"
+#include "exceptions.h"
 
 namespace mysqlpp {
 
@@ -23,7 +23,10 @@
 
 const ColData Row::lookup_by_name(const char* i) const
 {
-	return (*this)[res->field_num(std::string(i))];
+	int si = res->field_num(std::string(i));
+	if( si >= res->num_fields() )
+		throw BadFieldName(i, res->field_names());
+	return (*this)[si];
 }
 
 } // end namespace mysqlpp



Thread
[patch] BadFieldName exceptionChris Frey9 Feb
  • Re: [patch] BadFieldName exceptionWarren Young14 Feb