Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
path: root/atoidejouer/db/story.py
blob: d3865637b18a82105f18dd2c81d9537b7af659a3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
# python import
import logging

# get application logger
logger = logging.getLogger('atoidejouer')

# sqlite import
import sqlite3;

# atoidejouer import
from atoidejouer.tools import storage


class Key(object):

    def __init__(self, id=None, name=None, mime_type=None, timestamp=None, **kargs):
        """
        """
        self.id, self.name, self.mime_type, self.timestamp = id, name, mime_type, timestamp
        # ensure value if select row returns None value
        for arg in ['time', 'layer', 'x', 'y', 'duration', 'loop', 'path']:
            setattr(self, arg, kargs[arg] if arg in kargs and kargs[arg] else 0)

    def get_path(self):
        if self.path == 0:
            _ds_obj = None
            for _ds_obj in storage.journal_query({
                'mime_type': self.mime_type,
                'timestamp': self.timestamp,
                'title': self.name
                }):
                break
            self.path = _ds_obj.file_path if _ds_obj else 0
        return self.path

    def set_path(self, path):
        self.path = path

    def __repr__(self):
        return "%s|name=%s|mime_type=%s|timestamp=%s|time=%s|layer=%s|"\
                "x=%s|y=%s|dur=%s|loop=%s"\
                % (self.id, self.name, self.mime_type, self.timestamp,
                        self.time, self.layer,
                        self.x, self.y,
                        self.duration, self.loop)

    def __cmp__(self, other):
        return cmp(
                (self.name, self.mime_type, self.timestamp, self.time, self.layer),
                (other.name, other.mime_type, self.timestamp, other.time, other.layer)
                )

    def create(self):
        return "create table story("\
                "id integer primary key autoincrement not null,"\
                "name text,"\
                "mime_type text,"\
                "timestamp text,"\
                "time integer,"\
                "layer integer,"\
                "x integer,"\
                "y integer,"\
                "duration integer,"\
                "loop integer"\
                ")"

    def insert(self):
        columns = list()
        values  = list()
        for c in ['name', 'mime_type', 'timestamp', 'time', 'layer']:
            v = getattr(self, c)
            if v and v != -1:
                columns.append(c)
                values.append(str(v) if c in ['time', 'layer'] else "'%s'" % v)
        return "insert into story (%s) values (%s)" % (
                ",".join(columns),
                ",".join(values)
                )

    def _params(self, crit, joiner=" and "):
        values = list()
        for c in ['name', 'mime_type', 'time', 'layer', 'timestamp']:
            v = getattr(self, c)
            if v and v != -1:
                v = v if v in ['time', 'layer'] else "'%s'" % v
                values.append("%s=%s" % (c, v))
        return "%s %s" % (crit, joiner.join(values))

    def where(self):
        """Prepares simple where query according OO parameters.
        """
        return self._params("where")

    def set(self):
        """Prepares simple where query according OO parameters.
        """
        return self._params("set", joiner=",")

    def select(self):
        """Prepares simple select query according OO parameters.
        """
        return "select * from story %s" % self.where()

    def update(self):
        return "update story %s where id=%s" % (self.set(), self.id)

    def delete(self, all=False):
        """Prepares simple delete query according OO parameters.
        """
        q = "delete from story"
        if all is True:
            return q
        else:
            return "%s %s" % (q, self.where())


class DB(object):

    class __Singleton:

        def __init__(self, config=None, name="story", obj=Key):
            self.name, self.obj = name, obj
            db_path = storage.get_db_path('default')
            self.con = sqlite3.connect(db_path,
                    detect_types=sqlite3.PARSE_DECLTYPES)
            self.con.row_factory = sqlite3.Row
            self.__check()

        def __check(self):
            cur = self.con.cursor()
            # remove all first
            try:
                cur.execute("drop table %s" % self.name)
            except Exception, e:
                pass
            # create fresh db
            cur.execute(self.obj().create())
            # and close
            cur.close()

        def add(self, obj):
            cur = self.con.cursor()
            cur.execute(obj.insert())
            count = cur.rowcount
            cur.close()
            return count

        def _fetch(self, cur):
            row = cur.fetchone()
            while(row):
                yield self.obj(**row)
                row = cur.fetchone()

        def all(self):
            cur = self.con.cursor()
            cur.execute("select * from story")
            for obj in self._fetch(cur):
                yield obj
            cur.close()

        def get(self, obj):
            cur = self.con.cursor()
            cur.execute(obj.select())
            for obj in self._fetch(cur):
                yield obj
            cur.close()

        def one(self, obj):
            for one in self.get(obj):
                return one

        def get_layout_max(self):
            return 10

        def get_duration_max(self):
            return 10

        def update(self, obj):
            cur = self.con.cursor()
            cur.execute(obj.update())
            rowcount = cur.rowcount
            cur.close()
            return rowcount

        def _del(self, obj=None, all=False):
            cur = self.con.cursor()
            obj = self.obj() if obj is None else obj
            cur.execute(obj.delete(all=all))
            rowcount = cur.rowcount
            cur.close()
            return rowcount

    # singleton instance
    instance = None

    def __new__(c, force=False):
        """Singleton new init.
        """
        # if doesn't already initialized
        if not DB.instance\
        or force is True:
            # create a new instance
            DB.instance = DB.__Singleton()
        # return the manager object
        return DB.instance