0xGA: Check-in [19b06bb418]

Yet another PHP framework, but made for org-mode and geeks.

Many hyperlinks are disabled.
Use anonymous login to enable hyperlinks.

Overview
Comment:End Sqlite ORM feature
Timelines: family | ancestors | descendants | both | narv
Files: files | file ages | folders
SHA1:19b06bb418adc6c1fdf049d929168a142be27b7d
User & Date: milouse 2014-05-10 15:42:35
Context
2014-05-10
16:16
abstract sqlite management check-in: 054e202cac user: milouse tags: narv
15:42
End Sqlite ORM feature check-in: 19b06bb418 user: milouse tags: narv
2014-05-07
00:49
Add sqlite support and features to example app check-in: 66313b85fd user: milouse tags: narv
Changes

Changes to narv.

150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
...
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
                shift
                FOSSILFILE=`realpath $1`
                ;;
            --host|-H)
                shift
                DOMAINNAME=$1
                ;;
            console|create|init-chroot|restart|start|stop|-h|'help')
                COMMAND=$1
                ;;
            *)
                APPNAME=$1
                ;;
        esac
        shift
................................................................................
        ;;
    restart)
        narv_restart
        ;;
    init-chroot)
        init_chroot
        ;;
    console)
        cat <<EOF
Narv - Tiny org-mode file server - Console
Platform: `uname -o` `uname -r`; `python3 --version`
EOF
        while [ 0 ] ; do
            echo -n ">> "
            read SUBCOMMAND

            case $SUBCOMMAND in
                'help')
                    usage_help
                    ;;
                'bye'|'exit'|quit)
                    exit 0
                    ;;
                start)
                    narv_start
                    ;;
                stop)
                    narv_stop
                    ;;
                restart)
                    narv_restart
                    ;;
                init-chroot)
                    init_chroot
                    ;;
                *)
                    echo "Wrong command $SUBCOMMAND. Try help"
            esac
        done
        ;;
    *)
        echo "There's something strange
in your neighborhood.
Who ya gonna call?"
        ;;
esac







|







 







<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<






150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
...
438
439
440
441
442
443
444

































445
446
447
448
449
450
                shift
                FOSSILFILE=`realpath $1`
                ;;
            --host|-H)
                shift
                DOMAINNAME=$1
                ;;
            create|init-chroot|restart|start|stop|-h|'help')
                COMMAND=$1
                ;;
            *)
                APPNAME=$1
                ;;
        esac
        shift
................................................................................
        ;;
    restart)
        narv_restart
        ;;
    init-chroot)
        init_chroot
        ;;

































    *)
        echo "There's something strange
in your neighborhood.
Who ya gonna call?"
        ;;
esac

Changes to narv.py.

7
8
9
10
11
12
13

14
15
16
17
18
19
20
21
22



































































































































































































































23
24
25
26
27
28
29
import pwd
import grp
import sys
import signal
import urllib
import shutil
import fnmatch

import logging
import threading
import configparser
from datetime import date
from http.server import HTTPServer
from http.server import BaseHTTPRequestHandler
from socketserver import ThreadingMixIn
from configparser import ConfigParser






































































































































































































































class ResourceHelper:
    """ Utility to extract and expose various information on resources served """

    content_types = {
        'html': 'text/html; charset=utf-8',







>









>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
import pwd
import grp
import sys
import signal
import urllib
import shutil
import fnmatch
import sqlite3
import logging
import threading
import configparser
from datetime import date
from http.server import HTTPServer
from http.server import BaseHTTPRequestHandler
from socketserver import ThreadingMixIn
from configparser import ConfigParser


class DataObject:

    def __init__(self, appname, data=None):
        self.db_model()
        self.appname = appname
        self.errors = []
        self.rowid = 'new'
        self.db_path = 'var/db/{0}.db'.format(self.appname)

        if not os.path.isfile(self.db_path):
            self.db_install()

        if data != None:
            if type(data).__name__ == 'dict':
                if 'rowid' in data:
                    self.rowid = data['rowid']

                for name in self.data_attr:
                    if name in data:
                        self.data_attr[name] = data[name]

            else:
                self.find(data)


    def __getattr__(self, name):
        if name != 'data_attr' and name in self.data_attr:
            return self.data_attr[name]

        raise AttributeError


    def __setattr__(self, name, value):
        if name != 'data_attr' and name in self.data_attr:
            self.data_attr[name] = value
        else:
            # get the real class_name
            object.__setattr__(self, name, value)


    def is_new(self):
        return self.rowid == 'new'


    def find(self, value, crit='rowid', n=1):
        base_select = 'select rowid, * from {0}'.format(self.tablename)

        if crit == 'rowid':
            self.rowid = None
            request = '{0} where rowid = ?'.format(base_select)
        elif crit in self.data_attr:
            self.data_attr[crit] = None
            request = '{0} where {1} = ?'.format(base_select, crit)

        with sqlite3.connect(self.db_path) as db:
            db.row_factory = sqlite3.Row
            logging.debug('[DataObject] request "{0}" with {1}'.format(request, value))
            result = dict(db.execute(request, (value,)).fetchone())

        if len(result) > 0:
            if self.rowid == 'new' or self.rowid == None:
                self.rowid = result['rowid']

            for name in self.data_attr:
                if self.data_attr[name] == None and name in result:
                    self.data_attr[name] = result[name]


    def find_all(self, conditions):
        base_select = 'select rowid, * from {0}'.format(self.tablename)
        values = {}
        where_clause = []
        order_clause = ''
        limit_clause = ''

        for option in conditions:
            if option == 'order':
                order_opts = conditions['order'].split(' ')
                direction = 'asc'

                if len(order_opts) > 1:
                    order = order_opts[0]
                    if order_opts[1] == 'desc':
                        direction = 'desc'
                else:
                    order = order_opts

                if order in self.data_attr:
                    order_clause = ' order by {0} {1}'.format(order, direction)

            elif option == 'limit':
                values['limit'] = int(conditions['limit'])
                limit_clause = ' limit 0, :limit'

            elif option in self.data_attr:
                cond = 'LIKE'
                opt_val = None

                if type(conditions[option]).__name__ == 'dict':

                    if 'cond' in conditions[option]:
                        if conditions[option]['cond'] in ['>', '<', '=']:
                            cond = conditions[option]['cond']

                    if 'value' in conditions[option]:
                        opt_val = conditions[option]['value']

                else:
                    opt_val = conditions[option]

                if opt_val != None:
                    values[option] = optval
                    where_clause.append('{0} {1} :{0}'.format(option, cond))

        if len(where_clause) > 0:
            where_str = ' and '.join(where_clause)
        else:
            where_str = ''

        request = '{0}{1}{2}{3}'.format(
            base_select,
            where_str,
            order_clause,
            limit_clause)

        final_data = []
        current_object_type = type(self)

        with sqlite3.connect(self.db_path) as db:
            db.row_factory = sqlite3.Row
            cur = db.cursor()

            logging.debug('[DataObject] request "{0}" with {1}'.format(request, values))

            for row in cur.execute(request, values):
                final_data.append(current_object_type(self.appname, dict(row)))

        return final_data


    def validate(self):
        self.errors = []

        for name in self.data_attr:
            if self.data_attr[name] == None:
                self.errors.append(name)

        if len(self.errors) > 0:
            return False

        return True


    def merge(self):
        if self.rowid == 'new':
            return True

        if self.rowid != None:
            self.find(self.rowid)
            return self.validate()

        return False


    def save(self):
        values = {
            'rowid': self.rowid
        }

        if self.rowid == 'new':
            if not self.validate():
                return False

            values_insert = ''
            desc_insert = ''
            for name in self.data_attr:
                values[name] = self.data_attr[name]
                values_insert += ':{0}, '.format(name)
                desc_insert +=  '{0}, '.format(name)

            values_insert = values_insert[:-2]
            desc_insert = desc_insert[:-2]

            request = 'insert into {0}({1}) values({2})'.format(
                self.tablename,
                desc_insert,
                values_insert)

        else:
            if not self.merge():
                return False

            values_update = []

            for name in self.data_attr:
                values[name] = self.data_attr[name]
                values_update.append('{0} = :{0}'.format(name))

            request = 'update {0} set {1} where rowid = :rowid'.format(
                self.tablename,
                ', '.join(values_clause))

        logging.debug('[DataObject] request "{0}" with {1}'.format(request, values))
        total = 0

        db = sqlite3.connect(self.db_path)
        cur = db.cursor()
        cur.execute(request, values)
        if self.rowid == 'new' and total == 1:
            self.rowid = cur.lastrowid
        total = cur.rowcount
        db.commit()
        db.close()

        logging.debug('[DataObject] Last operation modifies {0} row, which rowid is {1}'.format(total, self.rowid))

        return total == 1


    def db_model(self):
        pass


    def db_install(self):
        pass



class ResourceHelper:
    """ Utility to extract and expose various information on resources served """

    content_types = {
        'html': 'text/html; charset=utf-8',