Node.js course · Part 5: Data · lab 5 of 9
Talking to a database
Why a real database rather than a file, queries that cannot be hijacked by their own values, the loop that quietly makes a hundred queries, and work that must either all happen or none of it.
By the end you can
- Say what a database gives you that a JSON file cannot
- Write queries where values can never become instructions
- Spot and fix the N+1 query, the commonest cause of a slow page
- Make several writes succeed or fail together
Easier if you did first
step 1 of 4
Why not just a file
The first time you need to save something, a JSON file looks perfect. Read it, change it, write it back. It works, and it keeps working until the day it does not.
Two requests arrive at once. Both read the file. Both change their own copy. Both write it back, and the second one overwrites the first. The order was never yours to control, and nothing told you it happened.
Then the file reaches ten thousand records and every read loads all of them to find one. Then your server restarts mid-write and the file is half a file.
A database solves exactly these. It handles many writers at once. It finds one row out of millions without reading the rest, because of an index. It will not leave half a change behind. And it can enforce rules, so a quote cannot point at a customer who does not exist.
Four questions on the things that actually bite.
What these words mean
- row
- One record: one quote, one customer.
- index
- A lookup structure so finding a row does not mean reading them all.
- transaction
- Several changes treated as one. All of them, or none.
- race condition
- Two things happening at once, and the result depends on which won.
- constraint
- A rule the database enforces, like 'this must point at a real customer'.
question 1 of 4
Two requests both read orders.json, add an order, and write it back. What happens?
question 2 of 4
What does an index on the email column actually do?
question 3 of 4
Why is building a query by joining strings dangerous?
question 4 of 4
You take payment and mark the order paid. The second write fails. What should happen?