On the one hand, this seems like a neat approach, having all the prepared statements in a struct. On the other hand, the compiler isn't really giving you any extra help, unless you do more work. By which I mean, instead of using a generic statement, create methods with the exact set of parameters, and wrap the call to execute the underlying prepared statement. That way, the compiler helps ensure that all the parameters to the statement are correct.
That might be an interesting approach. If the application won't benefit from that, however, this also seems like it might be optimizing the design for the wrong characteristics. The approach described prevents lazy loading - instead requiring preparing all statements when the application starts the connection...
As best I understand it, the better database drivers will cache all the prepared statements for you already. Which means it is safe to call Prepare() in the function where you need it. If the database has seen the Prepare() call before, and hasn't dropped it from its cache, it will simply use an already prepared version of the statement. Also, there's a distinction between calling Prepare() on the database, vs. calling Prepare() on a transaction. The result of Prepare() on the transaction is valid for the scope of the transaction, and shouldn't be called after the end of the transaction. Also, I suspect that Prepare() statements are not the bottleneck of the application, but whether or not they are, test before assuming!
Just to illustrate my point about different design characteristics, alternate approaches:
- A struct that has a "Prepare()" method that takes a label for what is to be prepared, rather than a statement. That way, if statements are already prepared, the Prepare() method can just look them up.
- Create an interface for the existing use of the DB object, and implement caching of Prepare() results yourself. (Do a performance check first, to see if this even matters!)
Difficult to tell which is the right approach, without further understanding of the requirements.
Eric.