Skip to content

Commit 512310f

Browse files
committed
Add "SQLite" and "MongoDB" recipes to new "Databases" chapter.
1 parent c17b3c3 commit 512310f

File tree

3 files changed

+177
-0
lines changed

3 files changed

+177
-0
lines changed

chapters/databases/index.html

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
---
2+
layout: chapter
3+
title: Databases
4+
chapter: Databases
5+
---
6+
7+
{% capture url %}/chapters/{{ page.chapter | replace: ' ', '_' | downcase }}{% endcapture %}
8+
{% capture indexurl %}{{ url }}/index.html{% endcapture %}
9+
10+
<ul>
11+
{% for page in site.pages %}
12+
{% if page.url contains url %}
13+
{% unless page.url == indexurl %}
14+
<li><a href="{{ page.url | replace: '.html', '' }}">{{ page.title }}</a></li>
15+
{% endunless %}
16+
{% endif %}
17+
{% endfor %}
18+
</ul>

chapters/databases/mongodb.md

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
---
2+
layout: recipe
3+
title: MongoDB
4+
chapter: Databases
5+
---
6+
## Problem
7+
8+
You need to interface with a MongoDB database.
9+
10+
## Solution
11+
12+
### For Node.js
13+
14+
### Setup
15+
* [Install MongoDB](http://www.mongodb.org/display/DOCS/Quickstart) on your computer if you have not already.
16+
17+
* [Install the native MongoDB module](https://github.com/christkv/node-mongodb-native).
18+
19+
#### Saving Records
20+
21+
{% highlight coffeescript %}
22+
mongo = require 'mongodb'
23+
24+
server = new mongo.Server "127.0.0.1", 27017, {}
25+
26+
client = new mongo.Db 'test', server
27+
28+
# save() updates existing records or inserts new ones as needed
29+
exampleSave = (dbErr, collection) ->
30+
console.log "Unable to access database: #{dbErr}" if dbErr
31+
collection.save { _id: "my_favorite_latte", flavor: "honeysuckle" }, (err, docs) ->
32+
console.log "Unable to save record: #{err}" if err
33+
client.close()
34+
35+
client.open (err, database) ->
36+
client.collection 'coffeescript_example', exampleSave
37+
{% endhighlight %}
38+
39+
#### Finding Records
40+
41+
{% highlight coffeescript %}
42+
mongo = require 'mongodb'
43+
44+
server = new mongo.Server "127.0.0.1", 27017, {}
45+
46+
client = new mongo.Db 'test', server
47+
48+
exampleFind = (dbErr, collection) ->
49+
console.log "Unable to access database: #{dbErr}" if dbErr
50+
collection.find({ _id: "my_favorite_latte" }).nextObject (err, result) ->
51+
if err
52+
console.log "Unable to find record: #{err}"
53+
else
54+
console.log result # => { id: "my_favorite_latte", flavor: "honeysuckle" }
55+
client.close()
56+
57+
client.open (err, database) ->
58+
client.collection 'coffeescript_example', exampleFind
59+
{% endhighlight %}
60+
61+
### For Browsers
62+
63+
A [REST-based interface](https://github.com/tdegrunt/mongodb-rest) is in the works. This will provide AJAX-based access.
64+
65+
## Discussion
66+
67+
This recipe breaks the *save* and *find* into separate examples in order to separate the MongoDB-specific concerns from the task of connection and callback management. The [async module](https://github.com/caolan/async) can help with that.

chapters/databases/sqlite.md

Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
---
2+
layout: recipe
3+
title: SQLite
4+
chapter: Databases
5+
---
6+
## Problem
7+
8+
You need to interface with a [SQLite](http://www.sqlite.org/) database from inside of Node.js.
9+
10+
## Solution
11+
12+
Use the [SQLite module](http://code.google.com/p/node-sqlite/).
13+
14+
{% highlight coffeescript %}
15+
sqlite = require 'sqlite'
16+
17+
db = new sqlite.Database
18+
19+
# The module uses asynchronous methods,
20+
# so we chain the calls the db.execute
21+
exampleCreate = ->
22+
db.execute "CREATE TABLE snacks (name TEXT(25), flavor TEXT(25))",
23+
(exeErr, rows) ->
24+
throw exeErr if exeErr
25+
exampleInsert()
26+
27+
exampleInsert = ->
28+
db.execute "INSERT INTO snacks (name, flavor) VALUES ($name, $flavor)",
29+
{ $name: "Potato Chips", $flavor: "BBQ" },
30+
(exeErr, rows) ->
31+
throw exeErr if exeErr
32+
exampleSelect()
33+
34+
exampleSelect = ->
35+
db.execute "SELECT name, flavor FROM snacks",
36+
(exeErr, rows) ->
37+
throw exeErr if exeErr
38+
console.log rows[0] # => { name: 'Potato Chips', flavor: 'BBQ' }
39+
40+
# :memory: creates a DB in RAM
41+
# You can supply a filepath (like './example.sqlite') to create/open one on disk
42+
db.open ":memory:", (openErr) ->
43+
throw openErr if openErr
44+
exampleCreate()
45+
{% endhighlight %}
46+
47+
## Discussion
48+
49+
You can also prepare your SQL queries beforehand:
50+
51+
{% highlight coffeescript %}
52+
sqlite = require 'sqlite'
53+
async = require 'async' # Not required but added to make the example more concise
54+
55+
db = new sqlite.Database
56+
57+
createSQL = "CREATE TABLE drinks (name TEXT(25), price NUM)"
58+
59+
insertSQL = "INSERT INTO drinks (name, price) VALUES (?, ?)"
60+
61+
selectSQL = "SELECT name, price FROM drinks WHERE price < ?"
62+
63+
create = (onFinish) ->
64+
db.execute createSQL, (exeErr) ->
65+
throw exeErr if exeErr
66+
onFinish()
67+
68+
prepareInsert = (name, price, onFinish) ->
69+
db.prepare insertSQL, (prepErr, statement) ->
70+
statement.bindArray [name, price], (bindErr) ->
71+
statement.fetchAll (fetchErr, rows) -> # Called so that it executes the insert
72+
onFinish()
73+
74+
prepareSelect = (onFinish) ->
75+
db.prepare selectSQL, (prepErr, statement) ->
76+
statement.bindArray [1.00], (bindErr) ->
77+
statement.fetchAll (fetchErr, rows) ->
78+
console.log rows[0] # => { name: "Mia's Root Beer", price: 0.75 }
79+
onFinish()
80+
81+
db.open ":memory:", (openErr) ->
82+
async.series([
83+
(onFinish) -> create onFinish,
84+
(onFinish) -> prepareInsert "LunaSqueeze", 7.95, onFinish,
85+
(onFinish) -> prepareInsert "Viking Sparkling Grog", 4.00, onFinish,
86+
(onFinish) -> prepareInsert "Mia's Root Beer", 0.75, onFinish,
87+
(onFinish) -> prepareSelect onFinish
88+
])
89+
{% endhighlight %}
90+
91+
The [SQLite version of SQL](http://www.sqlite.org/lang.html) and the [node-sqlite module documentation](https://github.com/orlandov/node-sqlite#readme) provide more complete information.
92+

0 commit comments

Comments
 (0)