contrib/tnitter: extract `DB` from `model` into `database`
[nit.git] / contrib / tnitter / src / database.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 # Database interface of Tnitter
16 module database
17
18 import sqlite3
19
20 import model
21
22 # The Tnitter database
23 class DB
24 super Sqlite3DB
25
26 redef init open(path)
27 do
28 super
29 create_tables
30 end
31
32 # Create the needed tables
33 fun create_tables
34 do
35 assert create_table("IF NOT EXISTS users (user TEXT PRIMARY KEY, pass TEXT)") else
36 print error or else "?"
37 end
38
39 assert create_table("IF NOT EXISTS posts (user TEXT, text TEXT, posted DATETIME DEFAULT CURRENT_TIMESTAMP)") else
40 print error or else "?"
41 end
42 end
43
44 # Check if the login credentials are valid
45 #
46 # If valid, returns the username at database creation time. Otherwise returns `null`.
47 fun check_login(user, pass: String): nullable String
48 do
49 var stmt = select("user FROM users WHERE lower({user.to_sql_string}) = lower(user) " +
50 "AND {pass.tnitter_hash.to_sql_string} = pass")
51 assert stmt != null else print error or else "?"
52
53 for row in stmt do return row[0].to_s
54 return null
55 end
56
57 # Try to sign up a new user, return `true` on success
58 fun sign_up(user, pass: String): Bool
59 do
60 # Check if already in user
61 var stmt = select("user FROM users WHERE lower({user.to_sql_string}) = lower(user)")
62 assert stmt != null else print error or else "?"
63
64 if not stmt.iterator.to_a.is_empty then return false
65
66 # Insert intro BD
67 assert insert("INTO users(user, pass) VALUES ({user.to_sql_string}, {pass.tnitter_hash.to_sql_string})") else
68 print error or else "?"
69 end
70
71 return true
72 end
73
74 # Tnit something
75 fun post(user, text: String)
76 do
77 assert insert("INTO posts(user, text) VALUES ({user.to_sql_string}, {text.to_sql_string})") else
78 print error or else "?"
79 end
80 end
81
82 # Get the latest tnits
83 fun latest_posts(count: Int): Array[Post]
84 do
85 var stmt = select("user, text FROM posts ORDER BY datetime(posted) DESC LIMIT {count}")
86 assert stmt != null else print error or else "?"
87
88 var posts = new Array[Post]
89 for row in stmt do posts.add new Post(row[0].to_s, row[1].to_s)
90
91 return posts
92 end
93 end