JOIN USING
[sqlgg.git] / overview.md
blob84a4cc983c1dd09a547a37e965503f788f2fb66d
1 sqlgg: SQL Guided (code) Generator
2 ==================================
4 Problem
5 -------
7 Writing database layer code is usually tedious and error-prone, due to the mix of different
8 languages. SQL queries constructed dynamically need to bind external data (from application), and
9 the resulting rowset must be decomposed into application native data. Data crossing these
10 application-to-database boundaries is what causes troubles. One can factor out all common database
11 communication code, hide the database under some application-specific abstraction, but one always
12 needs to manully specify correspondence between SQL query binding slots (or resulting rowset
13 columns) and code variables. This mapping should be updated manually every time SQL query is
14 modified. 
16 Solution
17 --------
19 SQL parser and code generator which ensures that application code and database queries are in sync.
20 It analyzes SQL query and determines the set of input parameters (values for INSERT, run-time
21 substitution parameters) and the set of resulting columns (for SELECT). Then it generates the C++
22 code which structures input and output values together as function parameters and assignes
23 corresponding native data types. So basically you provide an SQL query and generator creates a C++
24 function which takes the set of typed parameters as required to fill slots in a query. Generated
25 code binds provided parameters into query and executes it. SELECT statements additionally return the
26 collection of structures with fields representing columns of resulting rowset. The most fruitful
27 consequence of such approach is that the C++ compiler itself guarantees that SQL query will have all
28 parameters bound with correct types. So if you modify the query and forget to update the code -- the
29 compiler will point on errorneous parts.
31 Example
32 -------
34 Queries:
36     CREATE TABLE test (id INTEGER PRIMARY KEY AUTOINCREMENT,name TEXT,descr TEXT);
37     -- [sqlgg] name=Add
38     INSERT INTO test(name,descr) VALUES;
39     SELECT name,descr FROM test WHERE name = @name LIMIT @limit;
40     SELECT name,z FROM 
41       (SELECT name,
42               city || @delim || descr as y,
43               max(length(city),random(*)) as z 
44        FROM test 
45        LEFT JOIN (SELECT name AS city FROM test WHERE id=@id))
46     WHERE z < @level;
48 Generated code (with some boilerplate omitted):
50     // DO NOT EDIT MANUALLY
52     // generated by sqlgg 0.2.0 (3a96042c)
54     #pragma once
56     template <class Traits>
57     struct sqlgg
58     {
59       // CREATE TABLE test (id INTEGER PRIMARY KEY AUTOINCREMENT,name TEXT,descr TEXT)
60     public:
61       static bool create_test(typename Traits::connection db)
62       {
63         return Traits::do_execute(db,_T("CREATE TABLE test (id INTEGER PRIMARY KEY AUTOINCREMENT,name TEXT,descr TEXT)"),typename Traits::no_params());
64       }
66       // INSERT INTO test(name,descr) VALUES
67     private:
68       struct params_1;
70     public:
71       static bool Add(typename Traits::connection db, typename Traits::Text const& name, typename Traits::Text const& descr)
72       {
73         return Traits::do_execute(db,_T("INSERT INTO test(name,descr) VALUES (?,?)"),params_1(name, descr));
74       }
76       // SELECT name,descr FROM test WHERE name = @name LIMIT @limit
77     private:
78       template <class T>
79       struct output_2
80       {
81         static void of_stmt(typename Traits::statement stmt, T& obj)
82         {
83           Traits::get_column_Text(stmt, 0, obj.name);
84           Traits::get_column_Text(stmt, 1, obj.descr);
85         }
86       }; // struct output_2
88     private:
89       struct params_2;
91     public:
92       struct data_2
93       {
94         typename Traits::Text name;
95         typename Traits::Text descr;
96       }; // struct data_2
98     public:
99       template<class T>
100       static bool select_2(typename Traits::connection db, T& result, typename Traits::Text const& name, typename Traits::Int const& limit)
101       {
102         return Traits::do_select(db,result,_T("SELECT name,descr FROM test WHERE name = @name LIMIT @limit"),output_2<typename T::value_type>(),params_2(name, limit));
103       }
105       // SELECT name,z FROM 
106     //   (SELECT name,
107     //           city || @delim || descr as y,
108     //           max(length(city),random(*)) as z 
109     //    FROM test 
110     //    LEFT JOIN (SELECT name AS city FROM test WHERE id=@id))
111     // WHERE z < @level
112     private:
113       template <class T>
114       struct output_3
115       {
116         static void of_stmt(typename Traits::statement stmt, T& obj)
117         {
118           Traits::get_column_Text(stmt, 0, obj.name);
119           Traits::get_column_Int(stmt, 1, obj.z);
120         }
121       }; // struct output_3
123     private:
124       struct params_3;
126     public:
127       struct data_3
128       {
129         typename Traits::Text name;
130         typename Traits::Int z;
131       }; // struct data_3
133     public:
134       template<class T>
135       static bool select_3(typename Traits::connection db, T& result, typename Traits::Text const& delim, typename Traits::Int const& id, typename Traits::Int const& level)
136       {
137         return Traits::do_select(db,result,_T("SELECT name,z FROM \
138       (SELECT name,\
139               city || @delim || descr as y,\
140               max(length(city),random(*)) as z \
141        FROM test \
142        LEFT JOIN (SELECT name AS city FROM test WHERE id=@id))\
143     WHERE z < @level"),output_3<typename T::value_type>(),params_3(delim, id, level));
144       }
146     }; // struct sqlgg
148 Things to note above:
150 1. The generated code is parametrized by database-specific class `Traits`. It specifies the
151                 correspondence between SQL and native types, provides types for database connection and other
152                 details. `Traits` also implements actual code to execute statements. It should be implemented
153                 once for every specific database API.
154 2. The annotation `[sqlgg] name=Add` before the INSERT query specifies the name of the generated
155     function. NB: there is no need to write (?,?) after VALUES.
156 1. `Add()` function takes two data parameters, the values to INSERT into table (`params_1` is the
157     boilerplate code to bind these parameters into query).
158 3. `select_2()` returns data via `result` parameter. Hidden auxiliary class `output_2` is used to
159     bind columns of rowset to the fields of `T::value_type`, which should have fields `name` and
160     `descr` of type `Traits::Text` (otherwise it will fail to compile). For convenience a structure
161     satisfying the requirements for output type is generated alongside the function, `data_2` in
162     this particular case, so `std::vector<data_2>` for `result` is fine.
163 4. The types of parameters for `select_2` were inferred correctly (`limit` is `Int` and `name` is
164     `Text`. SQL is not a statically-typed language so the inferred types are based on some
165     reasonable assumptions.
166 5. Statement of arbitrary depth across many tables should be supported.
167 6. Statements are checked for correctness as far as generator is concerned, so it will detect
168                 syntax errors, non-existant columns in expressions, mismatched rowsets in compound statements,
169                 ambigous column names etc.
171 Details
172 -------
174 The idea is that the generator should take care only of semantic binding between SQL and code sides,
175 being as unobtrusive as possible. So the choice of the specific database and API is a programmer's 
176 choice. Similarly, queries to the database are expressed in plain SQL, so that the generator can be
177 easily plugged in any existing project -- just move all SQL statements used in the code to separate
178 file and feed it to generator.
180 Ditinguishing feature of **sqlgg** is that it starts off with SQL queries, not object models
181 or SQL table descriptions.
183 This is work in progress and there is plenty of room for improvement. For now the status of this
184 project is **works for me** .  I use it for some simple database-access code with
185 [sqlite3](http://sqlite.org) engine (using suitable [sqlite3_traits](sqlite3_helper.hpp) helper).
186 This project was started when I found myself editing existing code with tons of C++ wrappers for SQL
187 queries, each binding several parameters and decomposing results.
189 A framework should be a tool to save writing repetitive code, rather than a tool you use to avoid
190 understanding 'what lies beneath'. <http://c2.com/cgi/wiki?PerniciousIngrownSql>
192 Try it [online](sql.cgi).
194 TODO
195 ----
197 * distinguish predicates and expressions (research)
198 * choose better names for some common cases (WHERE id = ? etc)
199 * fix line numbers in error output
200 * resolve conflics in grammar, check precedences
201 * type-inferrer is too primitive
202 * detect statements on single tables and group the corresponding generated code in one class
203 * check names (functions and bindings) for uniqueness
204 * support/test other SQL engines
205 * generate code for more languages
206 * read SQL spec
207 * type check expressions
209 ----
210 2009-05-09
212 <style>
213 code { font-family: monospace; }
214 pre { background-color: #eee; border: 1px solid #0f0; }
215 :not(pre) > code { font-size: 1em; }
216 </style>