Metaprogramming

Metaprogramming is a programming technique in which computer programs are treated as data. It means that a program can read, generate, analyze or transform other programs, or even modify itself while running. In other words, metaprogramming is a way of writing programs that manipulate programs.

In DolphinDB, metacode is represented by enclosing objects or expressions within angle brackets "<" and ">" and is stored as the "CODE" data type. The metacode object cannot be directly executed. It must be evaluated using the eval function, which interprets expressions or objects contained within it.

For example, if the variable "a" is assigned the metacode <1 + 2 * 3>, evaluating "a" using the eval function will return the result of the expression 1 + 2 * 3, which is 7.
a = <1 + 2 * 3>
typestr(a);
// output: CODE 

eval(a);
// output: 7

DolphinDB metaprogramming facilitates the dynamic creation and manipulation of functions and SQL statements, allowing functions and SQL queries to be defined, modified, or executed during runtime.

Functional Metaprogramming enables users to dynamically generate, retrieve, and invoke function definitions. This approach is particularly useful for complex data analysis tasks, as it enhances code flexibility and reusability. It allows users to create more versatile functions that can adapt to various scenarios without requiring multiple specialized implementations.

SQL Metaprogramming allows users to dynamically generate SQL queries through built-in functions (like sql, sqlUpdate) or directly using <select statement> with macro variables. This approach is useful for:
  • Constructing SQL queries with varying query columns, tables, or filters as required. For instance, it can be used in a reporting system, where the front-end user can retrieve the necessary data by selecting required fields.
  • Working with wide tables with a vast number of columns with similar naming patterns or performing repetitive operations across multiple columns.