1407
|
1 local Luan = require "luan:Luan.luan"
|
|
2 local error = Luan.error
|
|
3 local ipairs = Luan.ipairs or error()
|
|
4 local stringify = Luan.stringify or error()
|
|
5 local to_string = Luan.to_string or error()
|
|
6 local Io = require "luan:Io.luan"
|
|
7 local Http = require "luan:http/Http.luan"
|
|
8 local Html = require "luan:Html.luan"
|
|
9 local html_encode = Html.encode or error()
|
|
10 local Sql = require "luan:sql/Sql.luan"
|
|
11
|
|
12
|
|
13 local Web_query = {}
|
|
14
|
|
15 local function style()
|
|
16 %>
|
|
17 body {
|
|
18 font-family: sans-serif;
|
|
19 margin: 2em 5%;
|
|
20 }
|
|
21 h2 {
|
|
22 margin-bottom: .5em;
|
|
23 }
|
|
24 input, textarea {
|
|
25 margin-top: 1em;
|
|
26 font: inherit;
|
|
27 }
|
|
28 input[type="submit"] {
|
|
29 cursor: pointer;
|
|
30 padding: .5em;
|
|
31 border-radius: 4px;
|
|
32 }
|
|
33 <%
|
|
34 end
|
|
35
|
|
36 local function form()
|
|
37 %>
|
|
38 <!doctype html>
|
|
39 <html>
|
|
40 <head>
|
|
41 <title>SQL</title>
|
|
42 <style>
|
|
43 <% style() %>
|
|
44 </style>
|
|
45 </head>
|
|
46 <body>
|
|
47 <h2>SQL Query</h2>
|
|
48 <form>
|
|
49 <div>
|
|
50 <textarea name="query" cols=80 rows=10 autofocus></textarea>
|
|
51 </div>
|
|
52 <div>
|
|
53 <input type="submit">
|
|
54 </div>
|
|
55 </form>
|
|
56 </body>
|
|
57 </html>
|
|
58 <%
|
|
59 end
|
|
60
|
|
61 local function result(db_spec)
|
|
62 local query_str = Http.request.parameters.query
|
|
63 local db = Sql.database(db_spec)
|
|
64 local query = db.query(query_str)
|
|
65 local cols = query.column_names()
|
|
66 %>
|
|
67 <!doctype html>
|
|
68 <html>
|
|
69 <head>
|
|
70 <title>SQL</title>
|
|
71 <style>
|
|
72 <% style() %>
|
|
73 table {
|
|
74 border-collapse: collapse;
|
|
75 font-size: smaller;
|
|
76 }
|
|
77 th, td {
|
|
78 text-align: left;
|
|
79 padding: .5em;
|
|
80 border: solid 1px #ddd;
|
|
81 }
|
|
82 pre {
|
|
83 font: inherit;
|
|
84 }
|
|
85 </style>
|
|
86 </head>
|
|
87 <body>
|
|
88 <h2>SQL Results</h2>
|
|
89 <p><b><pre><%=html_encode(query_str)%></pre></b></p>
|
|
90 <table>
|
|
91 <tr>
|
|
92 <%
|
|
93 for _, col in ipairs(cols) do
|
|
94 %>
|
|
95 <th><%=col%></th>
|
|
96 <%
|
|
97 end
|
|
98 %>
|
|
99 </tr>
|
|
100 <%
|
|
101 for result in query.results do
|
|
102 %>
|
|
103 <tr>
|
|
104 <%
|
|
105 for _, col in ipairs(cols) do
|
|
106 %>
|
|
107 <td><%=html_encode(to_string(result[col]))%></td>
|
|
108 <%
|
|
109 end
|
|
110 %>
|
|
111 </tr>
|
|
112 <%
|
|
113 end
|
|
114 %>
|
|
115 </table>
|
|
116 </body>
|
|
117 </html>
|
|
118 <%
|
|
119 db.close()
|
|
120 end
|
|
121
|
|
122 function Web_query.of(db_spec)
|
|
123 db_spec or error "db_spec is nil"
|
|
124
|
|
125 return function()
|
|
126 Io.stdout = Http.response.text_writer()
|
|
127 local query = Http.request.parameters.query
|
|
128 if Http.request.parameters.query ~= nil then
|
|
129 result(db_spec)
|
|
130 else
|
|
131 form()
|
|
132 end
|
|
133 end
|
|
134
|
|
135 end
|
|
136
|
|
137 return Web_query
|