forked from software-tools-books/js4ds
-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.tex
698 lines (576 loc) · 19.5 KB
/
db.tex
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
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
\chapter{Using a Database}\label{s:db}
Our data manager (\chapref{s:dataman}) got information from a single CSV file.
That's fine for testing purposes,
but real applications almost always use a database of some kind.
There are many options these days for what kind,
but \gref{g:relational-database}{relational databases} continue to be
the workhorses of the web.
Relational databases are manipulated using a language called \gref{g:sql}{SQL},
which originally stood for ``Structured Query Language''
and is pronounced ``sequel'' or ``ess cue ell'' depending on whether the speaker is
left or right handed.
(Alternatives are collectively known as \gref{g:nosql-database}{NoSQL databases},
and use many different storage models.)
We will use a SQL database because it's still the most common choice,
but we won't try to introduce SQL itself:
for that,
see \href{https://swcarpentry.github.io/sql-novice-survey/}{this short tutorial}.
As an example problem,
we will store information about workshops.
Our database begins with a single \gref{g:table}{table}
with three \gref{g:field}{fields}
and two \gref{g:record}{records}:
\begin{minted}{sql}
drop table if exists Workshop;
create table Workshop(
ident integer unique not null primary key,
name text unique not null,
duration integer not null -- duration in minutes
);
insert into Workshop values(1, "Building Community", 60);
insert into Workshop values(2, "ENIAC Programming", 150);
\end{minted}
In the rest of this tutorial,
we will build a class to handle our interactions with a SQLite database,
test it,
and then put a web service on top of it.
\section{Starting Point}\label{s:db-start}
Our class, imaginatively named \texttt{Database},
takes the path to the SQLite database file as a constructor parameter
and creates a \gref{g:connection-manager}{connection manager}
through which we can send queries and get results.
We will create one method for each query we want to run,
and one helper method to display query results.
We will give all of the query methods the same \gref{g:signature}{signature}
so that can be handled interchangeably.
The whole thing looks like this:
\begin{minted}{js}
const sqlite3 = require('sqlite3')
class Database {
constructor (path) {
this.db = new sqlite3.Database(path, sqlite3.OPEN_READWRITE, (err) => {
if (err) this.fail(`Database open error ${err} for "${path}"`)
})
}
getAll (args) {
this.db.all(Q_WORKSHOP_GET_ALL, [], (err, rows) => {
if (err) this.fail(err)
this.display(rows)
})
}
getOne (args) {
this.db.all(Q_WORKSHOP_GET_ONE, args, (err, rows) => {
if (err) this.fail(err)
this.display(rows)
})
}
display (rows) {
for (let r of rows) {
console.log(r)
}
}
fail (msg) {
console.log(msg)
process.exit(1)
}
}
\end{minted}
This makes a lot more sense once we see what the queries look like:
\begin{minted}{js}
const Q_WORKSHOP_GET_ALL = `
select
Workshop.ident as workshopId,
Workshop.name as workshopName,
Workshop.duration as workshopDuration
from
Workshop
`
const Q_WORKSHOP_GET_ONE = `
select
Workshop.ident as workshopId,
Workshop.name as workshopName,
Workshop.duration as workshopDuration
from
Workshop
where
Workshop.ident = ?
`
\end{minted}
It's easy to overlook,
but the query to get details of one workshop has a question mark \texttt{?} as the value of \texttt{Workshop.ident}.
This means that the query expects us to provide a parameter when we call it
that will be substituted in for the question mark
to specify which workshop we're interested in.
This is why the arguments passed to \texttt{getOne} as \texttt{args}
are then passed through to \texttt{db.all};
it's also why \texttt{getAll} takes an \texttt{args} parameter,
but ignores it and always passed \texttt{{[}{]}} (no extra values) to \texttt{db.all} when running the query.
All right:
what does the \gref{g:driver}{driver} look like?
\begin{minted}{js}
function main () {
const path = process.argv[2]
const action = process.argv[3]
const args = process.argv.splice(4)
const database = new Database(path)
database[action](args)
}
main()
\end{minted}
This is simple enough:
it gets the path to the database file,
the desired action,
and any extra arguments from \texttt{process.argv},
then creates an instance of the \texttt{Database} class and---um.
And then it calls \texttt{database{[}action{]}(args)},
which takes a moment to figure out.
What's going on here is that an instance of a class is just a special kind of object,
and we can always look up an object's fields by name using \texttt{object{[}name{]}},
so if the string \texttt{action} (taken from the command-line argument) is \texttt{getAll} or \texttt{getOne},
then \texttt{database{[}action{]}(args)} is either \texttt{database.getAll(args)} or database.getOne(args)\texttt{.\ This\ is\ clever,\ but\ if\ we\ ask\ for\ an\ action\ like\ }show\texttt{\ or\ }help\texttt{\ or\ }GetOne\texttt{\ (with\ an\ upper-case\ 'G'),\ then\ }database{[}action{]}` doesn't exist and we get a very confusing error message.
We really should try to do better\ldots{}
But before then,
let's try running this:
\begin{minted}{shell}
$ node database-initial.js fixture.db getAll
\end{minted}
\begin{minted}{text}
{ workshopId: 1,
workshopName: 'Building Community',
workshopDuration: 60 }
{ workshopId: 2,
workshopName: 'ENIAC Programming',
workshopDuration: 150 }
\end{minted}
That seems to have worked:
\texttt{getAll} was called,
and the result is an array of objects,
one per record,
whose names are the derived in an obvious way from the names of the columns.
\section{In-Memory Database}\label{s:db-in-memory}
The previous example always manipulates database on disk.
For testing purposes,
it's faster and safer to use an \gref{g:in-memory-database}{in-memory database}.
Let's modify the constructor of \texttt{Database} to set this up:
\begin{minted}{js}
constructor (mode, path) {
this.path = path
switch (mode) {
case 'memory' :
const setup = fs.readFileSync(this.path, 'utf-8')
this.db = new sqlite3.Database(':memory:', sqlite3.OPEN_READWRITE,
(err) => {
if (err) {
this.fail(`In-memory database open error "${err}"`)
}
})
this.db.exec(setup,(err) => {
if (err) {
this.fail(`Cannot initialize in-memory database from "${this.path}"`)
}
})
break
case 'file' :
this.db = new sqlite3.Database(this.path, sqlite3.OPEN_READWRITE,
(err) => {
if (err) {
this.fail(`Database open error ${err} for "${path}"`)
}
})
break
default :
this.fail(`Unknown mode "${mode}"`)
break
}
}
\end{minted}
If the \texttt{mode} parameter is the string \texttt{"memory"},
we create an in-memory database and initialize it by executing
a file full of setup commands specified by the user---in our case,
exactly the commands we showed at the start of the lesson.
If the \texttt{mode} is \texttt{"file"},
we interpret the file argument as the name of an on-disk database
and proceed as before.
We put our error messages in ALL CAPS because that's the most annoying option easily available to us.
Less annoyingly,
we can use destructuring to handle command-line arguments in the driver:
\begin{minted}{js}
function main () {
const [mode, path, action, ...args] = process.argv.splice(2)
const database = new Database(mode, path)
database[action](args)
}
\end{minted}
Here, the expression \texttt{...args} means
``take anything left over after the fixed names have been matched and put it in an array called \texttt{args}''.
With these changes in place,
we can run a query to get details of the second workshop like this:
\begin{minted}{shell}
$ node database-mode.js memory fixture.sql getOne 2
\end{minted}
\begin{minted}{text}
{ workshopId: 2,
workshopName: 'ENIAC Programming',
workshopDuration: 150 }
\end{minted}
After a bit of experimentation,
we decide to take this even further to make testing easier.
We will allow the driver to read the SQL script itself and pass that into \texttt{Database}
so that we can do the file I/O once and then repeatedly build a database in memory for testing.
That way,
each of our tests will start with the database in a known, predictable state,
regardless of what other tests may have run before
and what changes they might have made to the database.
Here are the changes to the constructor:
\begin{minted}{js}
constructor (mode, arg) {
switch (mode) {
case 'direct' :
this._inMemory(arg)
break
case 'memory' :
const setup = fs.readFileSync(arg, 'utf-8')
this._inMemory(setup)
break
case 'file' :
this._inFile(arg)
break
default :
this.fail(`Unknown mode "${mode}"`)
break
}
}
\end{minted}
And here are the supporting methods:
\begin{minted}{js}
_inMemory (script) {
this.db = new sqlite3.Database(':memory:', sqlite3.OPEN_READWRITE,
(err) => {
if (err) {
this.fail(`In-memory database open error "${err}"`)
}
})
this.db.exec(script,
(err) => {
if (err) {
this.fail(`Unable to initialize in-memory database from "${script}"`)
}
})
}
_inFile (path) {
this.db = new sqlite3.Database(path, sqlite3.OPEN_READWRITE, (err) => {
if (err) this.fail(`Database open error "${err}" for "${path}"`)
})
}
\end{minted}
We also need to change the driver
(and check, finally, that the requested action is actually supported):
\begin{minted}{js}
function main () {
let [mode, setup, action, ...args] = process.argv.splice(2)
if (mode === 'direct') {
setup = fs.readFileSync(setup, 'utf-8')
}
const database = new Database(mode, setup)
if (!(action in database)) {
database.fail(`No such operation "${action}"`)
}
database[action](args)
}
\end{minted}
\section{Making It Testable}\label{s:db-testable}
We put the database class and its driver in separate files
so that applications can load just the former.
We will now change the database query methods to return results for display
rather than displaying them directly,
since we will eventually want to compare them or return them to a server rather than printing them:
\begin{minted}{js}
class Database {
// ...as before...
getAll (args) {
this.db.all(Q_WORKSHOP_GET_ALL, [], (err, rows) => {
if (err) this.fail(err)
return rows
})
}
// ...as before...
}
\end{minted}
The driver then looks like this:
\begin{minted}{js}
const Database = require('./separate-database')
const display = (rows) => {
for (let r of rows) {
console.log(r)
}
}
const main = () => {
let [mode, path, action, ...args] = process.argv.splice(2)
const db = new Database(mode, path)
if (!(action in db)) {
db.fail(`No such operation "${action}"`)
}
const result = db[action](args)
display(result)
}
main()
\end{minted}
Let's try running it:
\begin{minted}{shell}
$ node separate-driver.js file fixture.db getAll
\end{minted}
\begin{minted}{text}
for (let r of rows) {
^
TypeError: Cannot read property 'Symbol(Symbol.iterator)' of undefined
at display (/project/src/db/separate-driver.js:4:15)
at main (/project/src/db/separate-driver.js:16:3)
\end{minted}
Whoops: the \texttt{run} method of the database delivers results to a callback;
its own result is therefore \texttt{undefined},
so there's nothing in the caller to print.
The solution is to give the \texttt{get} methods a callback of their own:
\begin{minted}{js}
class Database {
// ...as before...
getAll (args, callback) {
this.db.all(Q_WORKSHOP_GET_ALL, [], (err, rows) => {
if (err) this.fail(err)
callback(rows)
})
}
// ...as before...
}
\end{minted}
We then change the driver to pass \texttt{display} to the database method it's calling:
\begin{minted}{js}
const Database = require('./callback-database')
const display = (rows) => {
for (let r of rows) {
console.log(r)
}
}
const main = () => {
let [mode, path, action, ...args] = process.argv.splice(2)
const db = new Database(mode, path)
if (!(action in db)) {
db.fail(`No such operation "${action}"`)
}
db[action](args, display)
}
main()
\end{minted}
This looks strange the first few (dozen) times,
but it's the way JavaScript works:
instead of asking for something and then operating on it,
we say,
``Here's what we want to do once results are available.''
\section{Testing}\label{s:db-testing}
We can finally write some tests:
\begin{minted}{js}
const assert = require('assert')
const Database = require('./callback-database')
const FIXTURE = `
drop table if exists Workshop;
create table Workshop(
ident integer unique not null primary key,
name text unique not null,
duration integer not null -- duration in minutes
);
insert into Workshop values(1, "Building Community", 60);
insert into Workshop values(2, "ENIAC Programming", 150);
`
describe('database', () => {
it('should return all workshops', (done) => {
expected = [
{ workshopName: 'Building Community',
workshopDuration: 60, workshopId: 1 },
{ workshopName: 'ENIAC Programming',
workshopDuration: 150, workshopId: 2 }
]
new Database('direct', FIXTURE).getAll([], (results) => {
assert.deepEqual(results, expected,
'Got expected workshops')
done()
})
})
it('should return one workshop', (done) => {
expected = [
{ workshopName: 'Building Community',
workshopDuration: 60, workshopId: 1 }
]
new Database('direct', FIXTURE).getOne(1, (results) => {
assert.deepEqual(results, expected,
'Got single expected workshop')
done()
})
})
it('can only get workshops that exist', (done) => {
new Database('direct', FIXTURE).getOne(99, (results) => {
assert.deepEqual(results, [],
'Got no workshops matching nonexistent key')
done()
})
})
})
\end{minted}
Each test has the same structure:
we define the expected result,
create an entirely new database in memory,
and then call the method being tested,
passing it the fixture and the callback that will receives results.
That callback uses \texttt{assert} to check results
and \texttt{done} to signal that the test has completed.
\section{Updating the Database}\label{s:db-mutate}
The data manager we built in \chapref{s:dataman} only let us read data;
we couldn't modify it.
Let's add a bit more to our database class to support \gref{g:mutation}{mutation}:
\begin{minted}{js}
// ...imports as before...
const Q_WORKSHOP_GET_ALL = // ...as before...
const Q_WORKSHOP_GET_ONE = // ...as before...
const Q_WORKSHOP_ADD = `
insert into Workshop(name, duration) values(?, ?);
`
const Q_WORKSHOP_DELETE = `
delete from Workshop where ident = ?;
`
class Database {
constructor (mode, arg) {
// ...as before...
}
getAll (args, callback) {
// ...as before...
}
getOne (args, callback) {
// ...as before...
}
addOne (args, callback) {
this.db.run(Q_WORKSHOP_ADD, args, function (err, rows) {
if (err) this.fail(err)
callback([], this.lastID)
})
}
deleteOne (args, callback) {
this.db.run(Q_WORKSHOP_DELETE, args, (err, rows) => {
if (err) this.fail(err)
callback([], undefined)
})
}
fail (msg) {
// ...as before...
}
_inMemory (script) {
// ...as before...
}
_inFile (path) {
// ...as before...
}
}
module.exports = Database
\end{minted}
The additions are straightforward:
the query that does the work is passed to \texttt{this.db.run} along with the incoming arguments
that specify what is to be added or deleted,
and an empty list of rows is passed to the action callback
(since adding and deleting don't return anything).
Testing involves a little more typing,
since want to check that the database is in the right state after the operation:
\begin{minted}{js}
// ...imports as before...
const FIXTURE = // ...as before...
describe('mutating database', () => {
it('can add a workshop', (done) => {
const duration = 35, name = 'Creating Bugs'
const db = new Database('direct', FIXTURE)
db.addOne([name, duration], function (results, lastID) {
assert.deepEqual(results, [], 'Got empty list as result when adding')
assert.equal(lastID, 3, 'Got the correct last ID after adding')
db.getAll([], (results) => {
expected = [
{ workshopName: 'Building Community',
workshopDuration: 60, workshopId: 1 },
{ workshopName: 'ENIAC Programming',
workshopDuration: 150, workshopId: 2 },
{ workshopName: name,
workshopDuration: duration, workshopId: 3 }
]
assert.deepEqual(results, expected,
'Got expected workshops after add')
done()
})
})
})
it('can delete a workshop', (done) => {
const db = new Database('direct', FIXTURE)
db.deleteOne([1], (results, lastID) => {
assert.equal(lastID, undefined, 'Expected last ID to be undefined')
assert.deepEqual(results, [], 'Got empty list as result when deleting')
db.getAll([], (results) => {
expected = [
{ workshopName: 'ENIAC Programming',
workshopDuration: 150, workshopId: 2 }
]
assert.deepEqual(results, expected,
'Got expected workshops after delete')
done()
})
})
})
})
\end{minted}
\section{Exercises}\label{s:db-exercises}
\exercise{Copying Records}
Write a program that copies all the rows
from the table \texttt{Workshop} in a database \texttt{source.db}
to a table with the same name in a new database \texttt{backup.db}.
\exercise{Filtering Records}
Add a new method to the \texttt{Database} class
to get all workshops that are longer than a specified time:
\begin{minted}{js}
const db = new Database(path)
const rows = db.getLongerThan(100)
assert.deepEqual(rows, [
{workshopName: 'ENIAC Programming', workshopDuration: 150, workshopId: 2}
])
\end{minted}
Your \texttt{Database.getLongerThan} method's SQL query
will need to use a \texttt{where} clause
that selects specific records.
\exercise{More Filtering}
The SQL query encapsulated in the variable below can be used to
find all workshop whose duration falls within a range.
\begin{minted}{js}
const Q_WORKSHOP_DURATION_RANGE = `
select
Workshop.ident as workshopId,
Workshop.name as workshopName,
Workshop.duration as workshopDuration
from
Workshop
where
(Workshop.duration <= ?) and (Workshop.duration >= ?)
`
\end{minted}
What do the \texttt{?}s mean in this query?
Write another method for the \texttt{Database} class called \texttt{getWithinLengthRange({[}args{]})}
that uses this query, taking arguments from the commandline as before.
What happens when you provide the wrong number of arguments to this function? Or
if you provide them in the wrong order?
Can you write a test that provides more useful feedback than this?
\exercise{Handling Errors}
The \texttt{Database} class prints a message and exits when it detects an error.
This is bad practice,
and I should be ashamed of having done it.
The right thing to do is to \gref{g:throw}{throw}
an \gref{g:exception}{exception}
that main program can \gref{g:catch}{catch}
and handle however it wants.
\begin{enumerate}
\item
Modify the code to do this.
\item
Modify the tests to check that the right exceptions are thrown when they should be.
\end{enumerate}
\exercise{Using a Database with a Server}
Rewrite the capstone project in \chapref{s:capstone} to use a database instead of a file for data storage.