Metaprogramming can feel like magic. You call a function that you neither wrote nor imported from any library and, magically, it comes back with a result. Even more magical is how metaprogramming lets you do otherwise impossible things with your programming language. In “The Art of Metaprogramming”, Jonathan Bartlett’s developerWorks series, he lists three examples that illustrate the benefits of metaprogramming:
- You can use metaprogramming to pre-generate tables of data for use at run-time.
- In applications with large amounts of boilerplate code and limited ability to abstract this code cleanly into functions, you can use metaprogramming to create a mini-language to write the boilerplate for you at run-time, simplifying your own code.
- You can use metaprogramming to transform a programming language that promotes verbosity into one that celebrates terseness. In addition to making up for inadequate language design, this can also ease maintenance.
Examples abound. A famous one is Ruby On Rails’ ActiveRecord class inspired by Martin Fowler’s ActiveRecord design pattern. At least in early versions of Rails, you could simply create an empty class like the following:
class Employee < ActiveRecord::Base
and, assuming you had a division column and mgrlastnm
column in the employees table in your database, you could write code
Employee.find_by_division_and_mgrlastnm "Sales", "Simpson"
and it would just work. The Rails metaprogramming logic would detect
that such a function did not exist and would generate the missing
function at run-time.
So how does all this relate to SQL? In this post and others, I will answer that question and attempt to illustrate the benefits of metaprogramming in SQL PL.
Click here to read the rest of "Metaprogramming in SQL (Part 1)" at Keith's blog