Databases step by step
Store data that survives the end of the program. Describe tables, add and read rows, search, connect tables, ask questions, group a transaction, and keep everything in a file.
What you will learn#
- what a database, a table, a row and a key are,
- describing tables as data and creating them,
- insert, read, update, delete,
- searching safely with SQL parameters,
- relations between tables,
- queries, aggregates, transactions and file databases.
Database words#
| Word | Meaning |
|---|---|
| table | a list of rows of the same shape (like a spreadsheet sheet) |
| column | one field of every row (Title, Year) |
| row | one record |
| key | a column that identifies a row (Id); the database numbers it for you |
| foreign key | a column that holds the key of a row in another table (AuthorId) |
| SQL | the language of databases; you only need a little of it |
RingDotNet uses Entity Framework Core with SQLite, a database in one file (or in memory). You describe the tables as Ring data; there is no SQL to write for normal work.
Part 1: tables, rows, searches#
# databases step by step - a library catalog with Entity Framework Core
load "dotnet.ring"
using { "RingDotNet.Data" }
func main
# STEP 1. Describe the tables: [table name, [ [column, type, isKey, options], ... ]]
aSchema = [
["Authors",[
["Id","int",1], # a key of type int is numbered by the database
["Name","string",0,[["required",1],["unique",1]]]
]],
["Books",[
["Id","int",1],
["Title","string",0,[["required",1],["maxlength",80]]],
["Year","int",0,[["nullable",1]]],
["Copies","int",0,[["default",1]]],
["AuthorId","int",0,[["references","Authors"],["ondelete","cascade"]]] # a foreign key
]]
]
oDb = new RingDatabase("Data Source=:memory:",aSchema) # a SQLite database in memory
? "STEP 1: the database exists"
# STEP 2. Add rows. insert() gives back the key
nTolkien = oDb.insert("Authors",[["Name","J.R.R. Tolkien"]])
nLewis = oDb.insert("Authors",[["Name","C.S. Lewis"]])
oDb.insert("Books",[["Title","The Hobbit"],["Year",1937],["AuthorId",nTolkien],["Copies",3]])
oDb.insert("Books",[["Title","The Fellowship of the Ring"],["Year",1954],["AuthorId",nTolkien]])
oDb.insert("Books",[["Title","The Lion, the Witch and the Wardrobe"],["Year",1950],["AuthorId",nLewis]])
oDb.insert("Books",[["Title","A book with no year"],["AuthorId",nLewis]])
? "STEP 2: " + oDb.count("Authors") + " authors, " + oDb.count("Books") + " books"
# STEP 3. Read rows. A row is a list of [column, value] pairs: dbValue() reads one column
aRow = oDb.byKey("Books",1)
? nl + "STEP 3: book 1 is " + dbValue(aRow,"Title") + ", copies " + dbValue(aRow,"Copies")
? " book 4 has year [" + dbValue(oDb.byKey("Books",4),"Year") + "] (empty: the column allows no value)"
# STEP 4. Search with a SQL condition: {0} and {1} are parameters, never paste text into SQL yourself
? nl + "STEP 4: books after 1940:"
aBooks = oDb.where("Books","Year > {0}",[1940])
for aBook in aBooks
? " " + dbValue(aBook,"Title") + " (" + dbValue(aBook,"Year") + ")"
next
# STEP 5. Change and delete
oDb.update("Books",4,[["Year",1951],["Title","Prince Caspian"]])
? nl + "STEP 5: book 4 is now " + dbValue(oDb.byKey("Books",4),"Title")
oDb.remove("Books",2)
? " books left: " + oDb.count("Books")
# STEP 6. Mistakes are errors that you can catch: the database refuses wrong data
try
oDb.insert("Authors",[["Name","C.S. Lewis"]]) # the name must be unique
catch
? nl + "STEP 6: a duplicate author is refused"
done
try
oDb.insert("Books",[["Title","Orphan"],["AuthorId",99]]) # there is no author 99
catch
? " a book of a missing author is refused"
done
oDb.close()STEP 1: the database exists
STEP 2: 2 authors, 4 books
STEP 3: book 1 is The Hobbit, copies 3
book 4 has year [] (empty: the column allows no value)
STEP 4: books after 1940:
The Fellowship of the Ring (1954)
The Lion, the Witch and the Wardrobe (1950)
STEP 5: book 4 is now Prince Caspian
books left: 3
STEP 6: a duplicate author is refused
a book of a missing author is refusedStep by step#
Step 1 — the schema. A table is [name, [columns]]; a column is [name, type, isKey, options]. Types: int long double decimal string bool datetime bytes. ["Id","int",1] is a key, numbered automatically. Options make rules the database enforces:
| Option | Rule |
|---|---|
["required",1] | a value must be given |
["unique",1] | no two rows may have the same value |
["maxlength",80] | at most 80 characters |
["nullable",1] | the value may be missing (a number can be empty) |
["default",1] | the value to use when none is given |
["references","Authors"] | the value must be the key of a row in Authors |
["ondelete","cascade"] | deleting the author deletes the books too |
Step 2 — add rows. insert(table, values) takes a list of [column, value] pairs and returns the new key. count counts the rows.
Step 3 — read rows. A row is a list of [column, value] pairs; dbValue(aRow,"Title") reads one column, and returns "" for a missing value.
Step 4 — search. where(table, condition, parameters) takes SQL such as Year > {0} and the values for {0}, {1}... as a list. Always pass values as parameters: they are never mixed into the SQL text, so a user typing x' OR '1'='1 cannot break your query (this attack is called SQL injection).
Step 5 — change and delete. update(table, key, values) changes columns of one row; remove(table, key) deletes it.
Step 6 — mistakes are errors. The database refuses a duplicate in a unique column and a foreign key that points to nothing. Catch the error with try/catch.
Part 2: relations, queries, transactions, files#
# the tutorial "Databases step by step", part 2: relations, queries, transactions and a file database
load "dotnet.ring"
using {
"System.IO"
"RingDotNet.Data"
}
func main
cFile = new Path().Combine([new Path().GetTempPath(),"ringdotnet_library.db"])
if new File().Exists(cFile)
new File().Delete(cFile)
ok
aSchema = [
["Authors",[["Id","int",1],["Name","string",0,[["required",1]]]]],
["Books",[["Id","int",1],["Title","string",0],["Year","int",0],["Stars","double",0],
["AuthorId","int",0,[["references","Authors"],["ondelete","cascade"]]]]]
]
oDb = new RingDatabase("Data Source=" + cFile,aSchema) # a file: the data stays after the program ends
nTolkien = oDb.insert("Authors",[["Name","Tolkien"]])
nLewis = oDb.insert("Authors",[["Name","Lewis"]])
oDb.insert("Books",[["Title","The Hobbit"],["Year",1937],["Stars",4.7],["AuthorId",nTolkien]])
oDb.insert("Books",[["Title","The Fellowship of the Ring"],["Year",1954],["Stars",4.8],["AuthorId",nTolkien]])
oDb.insert("Books",[["Title","The Silmarillion"],["Year",1977],["Stars",4.1],["AuthorId",nTolkien]])
oDb.insert("Books",[["Title","Narnia"],["Year",1950],["Stars",4.5],["AuthorId",nLewis]])
# RELATIONS: the rows that belong to a row
? "Books by Tolkien:"
aBooks = oDb.children("Authors",nTolkien,"Books")
for aBook in aBooks
? " " + dbValue(aBook,"Title")
next
? "Narnia was written by " + dbValue(oDb.parent("Books",4,"Authors"),"Name")
? nl + "Authors with their books:"
aItems = oDb.include("Authors","Books")
for aItem in aItems
? " " + dbValue(aItem[1],"Name") + ": " + len(aItem[2]) + " book(s)"
next
# QUERIES: filter, sort and page with a query written as data
aBest = oDb.query("Books",[
["where",["Stars",">=",4.5]],
["orderby",[["Year","desc"]]],
["select",["Title","Year"]]
])
? nl + "Books with at least 4.5 stars, newest first:"
for aBook in aBest
? " " + dbValue(aBook,"Year") + " " + dbValue(aBook,"Title")
next
? nl + "Average stars : " + oDb.average("Books","Stars",[])
? "Best rating : " + oDb.max("Books","Stars",[])
? "Books per author:"
aGroups = oDb.groupCount("Books","AuthorId",[])
for aGroup in aGroups
? " author " + aGroup[1] + " -> " + aGroup[2]
next
# TRANSACTIONS: all or nothing
oDb.begin()
oDb.insert("Books",[["Title","Draft 1"],["Year",2024],["Stars",1],["AuthorId",nLewis]])
oDb.insert("Books",[["Title","Draft 2"],["Year",2024],["Stars",1],["AuthorId",nLewis]])
? nl + "Books inside the transaction: " + oDb.count("Books")
oDb.rollback()
? "Books after rollback : " + oDb.count("Books")
# THE FILE: close the database, open it again, the data is still there
oDb.close()
oAgain = new RingDatabase("Data Source=" + cFile,aSchema)
? nl + "After reopening the file: " + oAgain.count("Books") + " books"
oAgain.close()
new File().Delete(cFile)Books by Tolkien:
The Hobbit
The Fellowship of the Ring
The Silmarillion
Narnia was written by Lewis
Authors with their books:
Tolkien: 3 book(s)
Lewis: 1 book(s)
Books with at least 4.5 stars, newest first:
1954 The Fellowship of the Ring
1950 Narnia
1937 The Hobbit
Average stars : 4.53
Best rating : 4.80
Books per author:
author 1 -> 3
author 2 -> 1
Books inside the transaction: 6
Books after rollback : 4
After reopening the file: 4 booksRelations#
children("Authors", key, "Books") gives the books of an author; parent("Books", key, "Authors") gives the author of a book; include("Authors","Books") gives every author with their books in one call.
Queries as data#
For more than a simple condition, write the query as a list:
oDb.query("Books",[
["where",["Stars",">=",4.5]],
["orderby",[["Year","desc"]]],
["select",["Title","Year"]]
])A condition is [column, operator, value] with = != < <= > >= contains startswith endswith in isnull notnull, and can be combined with ["and", c1, c2], ["or", ...], ["not", c]. sum, min, max, average, countWhere and groupCount summarise.
Transactions#
A transaction groups changes: begin(), several changes, then commit() to keep them or rollback() to cancel all. The program adds two drafts, sees six books, rolls back and sees four again.
A file database#
"Data Source=" + cFile stores the database in a file. The program closes it, opens it again and finds the four books: the data survives the program.
What you learned#
- describe the schema as data, let the database enforce the rules,
- parameters, never pasted text,
- relations with foreign keys,
- queries, aggregates, transactions, files.
Exercises#
- Add a
Memberstable and aLoanstable (a member borrows a book) and list who has which book. - Write a function that lists the authors with no books.
- Use
migrate()after adding aPagescolumn to the schema (Entity Framework). - Use
RingEntityDbfor the same data and compare (Entity Framework).