1 import sqlalchemy
as sql
2 from time
import strftime
5 # http://www.sqlalchemy.org/docs/04/intro.html#overview_sqlalchemy
6 DATABASE_PATH
= "sqlite://../../django/irclog/django_sqlite3_database.db"
8 class _DatabaseConnection(object):
9 """Connect to database.
10 Class name starts with `_` becouse it's not a plugin - it's privete class
11 and it shouldn't be loaded
13 def __init__(self
, dblink
):
14 """Create database connection"""
15 self
.database
= sql
.create_engine(dblink
)
16 metadata
= sql
.MetaData(self
.database
)
17 self
.message
= sql
.Table('log_message', metadata
, autoload
=True)
18 self
.user
= sql
.Table('log_user', metadata
, autoload
=True)
20 def add_msg(self
, user_id
, text
):
21 """Add new message. Doesn't check if user_id exist"""
22 # example 2008-02-17 18:03:46.072746
24 now
= strftime("%Y-%m-%d %H:%M:%S.000000")
25 text
= unicode(text
, encoding
="utf-8")
26 i
= self
.message
.insert()
27 i
.execute(user_id_id
=user_id
, date
=now
, text
=text
)
29 def add_user(self
, nick
):
30 """Add new user. Doesn't check if allready exist
33 i
= self
.user
.insert()
34 i
.execute(nick_name
=nick
, first_name
='', last_name
='',
35 about
='', homepage
='', email
='', avatar
='')
36 return self
.get_user(nick
)
38 def get_user(self
, nick
):
39 """Find user and returns his id, or None if doesn't exist"""
40 s
= self
.user
.select(self
.user
.c
.nick_name
== nick
)
42 return s
.execute().fetchone()[0]
48 self
.db
= _DatabaseConnection(DATABASE_PATH
)
51 def __call__(self
, server
):
52 if server
.msg_data
['command'] in ('join', 'quit', 'part'):
53 msg
= " ******* " + server
.msg_data
['command']
54 elif server
.msg_data
['command'] == 'pubmsg':
55 msg
= server
.msg_data
['args'][0]
57 # do nothing, just end
59 nick
= server
.msg_data
['user']
60 if not nick
in self
.users
.keys():
61 self
.users
[nick
] = self
.db
.get_user(nick
)
62 if not self
.users
[nick
]:
63 self
.users
[nick
] = self
.db
.add_user(nick
)
65 if msg
[1:].startswith('ACTION'):
66 msg
= "**" + msg
[7:-1]
67 # add message to database
68 self
.db
.add_msg(self
.users
[nick
], msg
)