1 # This file is part of NIT ( http://www.nitlanguage.org ).
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
7 # http://www.apache.org/licenses/LICENSE-2.0
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.
15 # Database interface of Tnitter
22 # The Tnitter database
32 # Create the needed tables
35 assert create_table
("IF NOT EXISTS users (user TEXT PRIMARY KEY, pass TEXT)") else
36 print error
or else "?"
39 assert create_table
("IF NOT EXISTS posts (user TEXT, text TEXT, posted DATETIME DEFAULT CURRENT_TIMESTAMP)") else
40 print error
or else "?"
44 # Check if the login credentials are valid
46 # If valid, returns the username at database creation time. Otherwise returns `null`.
47 fun check_login
(user
, pass
: String): nullable String
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 "?"
53 for row
in stmt
do return row
[0].to_s
57 # Try to sign up a new user, return `true` on success
58 fun sign_up
(user
, pass
: String): Bool
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 "?"
64 if not stmt
.iterator
.to_a
.is_empty
then return false
67 assert insert
("INTO users(user, pass) VALUES ({user.to_sql_string}, {pass.tnitter_hash.to_sql_string})") else
68 print error
or else "?"
75 fun post
(user
, text
: String)
77 assert insert
("INTO posts(user, text) VALUES ({user.to_sql_string}, {text.to_sql_string})") else
78 print error
or else "?"
82 # Get the latest tnits
83 fun latest_posts
(count
: Int): Array[Post]
85 var stmt
= select
("user, text FROM posts ORDER BY datetime(posted) DESC LIMIT {count}")
86 assert stmt
!= null else print error
or else "?"
88 var posts
= new Array[Post]
89 for row
in stmt
do posts
.add
new Post(row
[0].to_s
, row
[1].to_s
)