summaryrefslogtreecommitdiff
path: root/doc/context/sources/general/manuals/sql/sql-mkiv.tex
blob: 4d2ecbc6e9b857c079ccd85ad7ae63d72fc34fd4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
% language=uk

% author    : Hans Hagen
% copyright : PRAGMA ADE & ConTeXt Development Team
% license   : Creative Commons Attribution ShareAlike 4.0 International
% reference : pragma-ade.nl | contextgarden.net | texlive (related) distributions
% origin    : the ConTeXt distribution
%
% comment   : Because this manual is distributed with TeX distributions it comes with a rather
%             liberal license. We try to adapt these documents to upgrades in the (sub)systems
%             that they describe. Using parts of the content otherwise can therefore conflict
%             with existing functionality and we cannot be held responsible for that. Many of
%             the manuals contain characteristic graphics and personal notes or examples that
%             make no sense when used out-of-context.
%
% comment   : Some chapters might have been published in TugBoat, the NTG Maps, the ConTeXt
%             Group journal or otherwise. Thanks to the editors for corrections. Also thanks
%             to users for testing, feedback and corrections.

\usemodule[art-01,abr-02]

\definecolor
  [maincolor]
  [r=.4]

\setupbodyfont
  [10pt]

\setuptype
  [color=maincolor]

\setuptyping
  [color=maincolor]

\definefont
  [TitlePageFont]
  [file:lmmonolt10-bold.otf]

\setuphead
  [color=maincolor]

\usesymbols
  [cc]

\setupinteraction
  [hidden]

\startdocument
  [metadata:author=Hans Hagen,
   metadata:title=SQL in ConTeXt,
   author=Hans Hagen,
   affiliation=PRAGMA ADE,
   location=Hasselt NL,
   title=SQL in \CONTEXT,
   support=www.contextgarden.net,
   website=www.pragma-ade.nl]

\startMPpage

    StartPage ;

    numeric w ; w := bbwidth(Page) ;
    numeric h ; h := bbheight(Page) ;

    fill Page withcolor \MPcolor{maincolor} ;

    draw textext.urt("\TitlePageFont Q")       xysized (1.1   w,0.9 h) shifted (-.05w,.05h) withcolor .20white ;
    draw textext.top("\TitlePageFont SQL")     xysized (0.4725w,0.13h) shifted (.675w,.24w) withcolor .60white ;
    draw textext.top("\TitlePageFont CONTEXT") xsized  (0.6   w)       shifted (.675w,.10w) withcolor .60white ;

    StopPage ;

\stopMPpage

\startsubject[title=Contents]

\placelist[section][alternative=a]

\stopsubject

\startsection[title=Introduction]

Although \CONTEXT\ is a likely candidate for typesetting content that comes from
databases it was only in 2011 that I ran into a project where a connection was
needed. After all, much document related typesetting happens on files or
dedicated storage systems.

Because we run most projects in an infrastructure suitable for \TEX, it made
sense to add some helper scripts to the \CONTEXT\ core distribution that deal
with getting data from (in our case) \MYSQL\ databases. That way we can use the
already stable infrastructure for installing and updating files that comes with
\CONTEXT.

As \LUA\ support is nicely integrated in \CONTEXT, and as dealing with
information from databases involves some kind of programming anyway, there is (at
least currently) no \TEX\ interface. The examples shown here work in \CONTEXT,
but you need to keep in mind that \LUA\ scripts can also use this interface.

{\em Although this code is under construction the interfaces are unlikely to
change, if only because we use it in production.}

\stopsection

\startsection[title=Presets]

In order to consult a database you need to provide credentials. You also need
to reach the database server, either by using some client program or via a
library. More about that later.

Because we don't want to key in all that information again and again, we will
collect it in a table. This also permits us to store it in a file and load it
on demand. For instance:

\starttyping
local presets = {
    database = "test",
    username = "root",
    password = "none",
    host     = "localhost",
    port     = 3306,
}
\stoptyping

You can put a table in a file \type {presets.lua} like this:

\starttyping
return {
    database = "test",
    username = "root",
    password = "none",
    host     = "localhost",
    port     = 3306,
}
\stoptyping

and then load it as follows:

\starttyping
local presets = table.load("presets.lua")
\stoptyping

A \type {sqlite} database has a much simpler preset. The default suffix of the
file is \type {db}. The other fields are just ignored.

\starttyping
return {
    database = "test",
}
\stoptyping

If you really want, you can use some library to open a connection, execute a
query, collect results and close the connection, but here we use just one
function that does it all. The presets are used to access the database and the
same presets will be used more often it makes sense to keep a connection open as
long as possible. That way you can execute much more queries per second,
something that makes sense when there are many small ones, as in web related
services. A connection is made persistent when the presets have an \type {id}
key, like

\starttyping
presets.id = "myproject"
\stoptyping

\stopsection

\startsection[title=Templates]

A query often looks like this:

\starttyping
SELECT
    `artist`, `title`
FROM
    `cd`
WHERE
    `artist` = 'archive' ;
\stoptyping

However, often you want to use the same query for multiple lookups, in which case
you can do this:

\starttyping
SELECT
    `artist`, `title`
FROM
    `cd`
WHERE
    `artist` = '%artist%' ;
\stoptyping

In the next section we will see how \type {%artist%} can be replaced by a more
meaningful value. You can a percent sign by entering two in a row: \type {%%}.

As with any programming language that deals with strings natively, you need a
way to escape the characters that fence the string. In \SQL\ a field name is
fenced by \type {``} and a string by \type {''}. Field names can often be
used without \type {``} but you can better play safe.

\starttyping
`artist` = 'Chilly Gonzales'
\stoptyping

Escaping of the \type {'} is simple:

\starttyping
`artist` = 'Jasper van''t Hof'
\stoptyping

When you use templates you often pass a string as variable and you don't want to
be bothered with escaping them. In the previous example we used:

\starttyping
`artist` = '%artist%'
\stoptyping

When you expect embedded quotes you can use this:

\starttyping
`artist` = '%[artist]%'
\stoptyping

In this case the variable {artist} will be escaped. When we reuse a template we
store it in a variable:

\starttyping
local template = [[
    SELECT
        `artist`, `title`
    FROM
        `cd`
    WHERE
        `artist` = '%artist%' ;
]]
\stoptyping

\stopsection

\startsection[title=Queries]

In order to execute a query you need to pass the previously discussed presets
as well as the query itself.

\starttyping
local data, keys = utilities.sql.execute {
    presets   = presets,
    template  = template,
    variables = {
        artist = "Porcupine Tree",
    },
}
\stoptyping

The variables in the presets table can also be passed at the outer
level. In fact there are three levels of inheritance: settings, presets
and module defaults.

\starttabulate
\NC presets        \NC a table with values \NC \NR
\NC template       \NC a query string \NC \NR
\NC templatefile   \NC a file containing a template \NC \NR
\NC \em resultfile \NC a (temporary) file to store the result \NC \NR
\NC \em queryfile  \NC a (temporary) file to store a query \NC \NR
\NC variables      \NC variables that are subsituted in the template \NC \NR
\NC username       \NC used to connect to the database \NC \NR
\NC password       \NC used to connect to the database \NC \NR
\NC host           \NC the \quote {machine} where the database server runs on \NC \NR
\NC port           \NC the port where the database server listens to \NC \NR
\NC database       \NC the name of the database \NC \NR
\stoptabulate

The \type {resultfile} and \type {queryfile} parameters are used when a client
approach is used. When a library is used all happens in memory.

When the query succeeds two tables are returned: \type {data} and \type {keys}. The
first is an indexed table where each entry is a hash. So, if we have only one
match and that match has only one field, you get something like this:

\starttyping
data = {
    {
        key = "value"
    }
}

keys = {
    "key"
}
\stoptyping

\stopsection

\startsection[title=Converters]

All values in the result are strings. Of course we could have provided some
automatic type conversion but there are more basetypes in \MYSQL\ and some are
not even standard \SQL. Instead the module provides a converter mechanism

\starttyping
local converter = utilities.sql.makeconverter {
    { name = "id",      type = "number" },
    { name = "name",    type = "string" },
    { name = "enabled", type = "boolean" },
}
\stoptyping

You can pass the converter to the execute function:

\starttyping
local data, keys = utilities.sql.execute {
    presets   = presets,
    template  = template,
    converter = converter,
    variables = {
        name = "Hans Hagen",
    },
}
\stoptyping

In addition to numbers, strings and booleans you can also use a function
or table:

\starttyping
local remap = {
    ["1"] = "info"
    ["2"] = "warning"
    ["3"] = "debug"
    ["4"] = "error"
}

local converter = utilities.sql.makeconverter {
    { name = "id",     type = "number" },
    { name = "status", type = remap },
}
\stoptyping

I use this module for managing \CONTEXT\ jobs in web services. In that case we
need to store jobtickets and they have some common properties. The definition of
the table looks as follows: \footnote {The tickets manager is part of the
\CONTEXT\ distribution.}

\starttyping
CREATE TABLE IF NOT EXISTS %basename% (
    `id`        int(11)     NOT NULL AUTO_INCREMENT,
    `token`     varchar(50) NOT NULL,
    `subtoken`  INT(11)     NOT NULL,
    `created`   int(11)     NOT NULL,
    `accessed`  int(11)     NOT NULL,
    `category`  int(11)     NOT NULL,
    `status`    int(11)     NOT NULL,
    `usertoken` varchar(50) NOT NULL,
    `data`      longtext    NOT NULL,
    `comment`   longtext    NOT NULL,

    PRIMARY KEY                     (`id`),
    UNIQUE INDEX `id_unique_index`  (`id` ASC),
    KEY          `token_unique_key` (`token`)
)
DEFAULT CHARSET = utf8 ;
\stoptyping

We can register a ticket from (for instance) a web service and use an independent
watchdog to consult the database for tickets that need to be processed. When the
job is finished we register this in the database and the web service can poll for
the status.

It's easy to imagine more fields, for instance the way \CONTEXT\ is called, what
files to use, what results to expect, what extra data to pass, like style
directives, etc. Instead of putting that kind of information in fields we store
them in a \LUA\ table, serialize that table, and put that in the data field.

The other way around is that we take this data field and convert it back to \LUA.
For this you can use a helper:

\starttyping
local results = utilities.sql.execute { ... }

for i=1,#results do
    local result = results[i]
    result.data = utilities.sql.deserialize(result.data)
end
\stoptyping

Much more efficient is to use a converter:

\starttyping
local converter = utilities.sql.makeconverter {
    ...
    { name = "data", type = "deserialize" },
    ...
}
\stoptyping

This way you don't need to loop over the result and deserialize each data
field which not only takes less runtime (often neglectable) but also takes
less (intermediate) memory. Of course in some cases it can make sense to
postpone the deserialization.

A variant is not to store a serialized data table, but to store a key|-|value
list, like:

\starttyping
data = [[key_1="value_1" key_2="value_2"]]
\stoptyping

Such data fields can be converted with:

\starttyping
local converter = utilities.sql.makeconverter {
    ...
    { name = "data", type = utilities.parsers.keq_to_hash },
    ...
}
\stoptyping

You can imagine more converters like this, and if needed you can use them to
preprocess data as well.

\starttabulate[|Tl|p|]
\NC "boolean"     \NC This converts a string into the value \type {true} or \type {false}.
                      Valid values for \type {true} are: \type {1}, \type {true}, \type
                      {yes}, \type {on} and \type {t} \NC \NR
\NC "number"      \NC This one does a straightforward \type {tonumber} on the value. \NC \NR
\NC function      \NC The given function is applied to value. \NC \NR
\NC table         \NC The value is resolved via the given table. \NC \NR
\NC "deserialize" \NC The value is deserialized into \LUA\ code. \NC \NR
\NC "key"         \NC The value is used as key which makes the result table is now hashed
                      instead of indexed. \NC \NR
\NC "entry"       \NC An entry is added with the given name and optionally with a default
                      value. \NC \NR
\stoptabulate

\stopsection

\startsection[title=Typesetting]

For good reason a \CONTEXT\ job often involves multiple passes. Although the
database related code is quite efficient it can be considered a waste of time
and bandwidth to fetch the data several times. For this reason there is
another function:

\starttyping
local data, keys = utilities.sql.prepare {
    tag = "table-1",
    ...
}

-- do something useful with the result

local data, keys = utilities.sql.prepare {
    tag = "table-2",
    ...
}

-- do something useful with the result
\stoptyping

The \type {prepare} alternative stores the result in a file and reuses
it in successive runs.

\stopsection

\startsection[title=Methods]

Currently we have several methods for accessing a database:

\starttabulate
\NC client  \NC use the command line tool, pass arguments and use files \NC \NR
\NC library \NC use the standard library (somewhat tricky in \LUATEX\ as we need to work around bugs) \NC \NR
\NC lmxsql  \NC use the library with a \LUA\ based pseudo client (stay in the \LUA\ domain) \NC \NR
\NC swiglib \NC use the (still experimental) library that comes with \LUATEX \NC \NR
\stoptabulate

All methods use the same interface (\type {execute}) and hide the dirty details
for the user. All return the data and keys tables and all take care of the proper
escaping and parsing.

\stopsection

\startsection[title=Helpers]

There are some helper functions and extra modules that will be described when
they are stable.

There is an \quote {extra} option to the \type {context} command that can be used
to produce an overview of a database. You can get more information about this
with the command:

\starttyping
context --extra=sql-tables --help
\stoptyping

\stopsection

\startsection[title=Example]

The distribution has a few examples, for instance a logger. The following code shows
a bit of this (we assume that the swiglib sqlite module is present):

\startbuffer
require("util-sql")
utilities.sql.setmethod("sqlite")
require("util-sql-loggers")

local loggers = utilities.sql.loggers

local presets = {
 -- method    = "sqlite",
    database  = "loggertest",
    datatable = "loggers",
    id        = "loggers",
}

os.remove("loggertest.db") -- start fresh

local db = loggers.createdb(presets)

loggers.save(db, { -- variant 1: data subtable
    type   = "error",
    action = "process",
    data   = { filename = "test-1", message = "whatever a" }
} )

loggers.save(db, { -- variant 2: flat table
    type     = "warning",
    action   = "process",
    filename = "test-2",
    message  = "whatever b"
} )

local result = loggers.collect(db, {
    start = {
        day   = 1,
        month = 1,
        year  = 2016,
    },
    stop = {
        day   = 31,
        month = 12,
        year  = 2116,
    },
    limit  = 1000000,
 -- type   = "error",
    action = "process"
})

context.starttabulate { "||||||" }
for i=1,#result do
    local r = result[i]
    context.NC() context(r.time)
    context.NC() context(r.type)
    context.NC() context(r.action)
    if r.data then
        context.NC() context(r.data.filename)
        context.NC() context(r.data.message)
    else
        context.NC()
        context.NC()
    end
    context.NC() context.NR()
end
context.stoptabulate()

-- local result = loggers.cleanup(db, {
--     before = {
--         day   = 1,
--         month = 1,
--         year  = 2117,
--     },
-- })
\stopbuffer

\typebuffer

In this example we typeset the (small) table):

\ctxluabuffer

\stopsection

\startsection[title=Colofon]

\starttabulate[|B|p|]
\NC author    \NC \getvariable{document}{author}, \getvariable{document}{affiliation}, \getvariable{document}{location} \NC \NR
\NC version   \NC \currentdate \NC \NR
\NC website   \NC \getvariable{document}{website} \endash\ \getvariable{document}{support} \NC \NR
\NC copyright \NC \symbol[cc][cc-by-sa-nc] \NC \NR
\stoptabulate

\stopsection

\stopdocument