data.py 1.59 KB
Newer Older
Vladislav Rykov's avatar
Vladislav Rykov committed
1
from psycopg2 import sql
Vladislav Rykov's avatar
Vladislav Rykov committed
2
from app.helpers.misc import with_psql
Vladislav Rykov's avatar
Vladislav Rykov committed
3
4
5


@with_psql
Vladislav Rykov's avatar
Vladislav Rykov committed
6
7
def create_table(cur, appkey, devid):
    tn = 'dev_' +str(appkey)+ '_' +str(devid)
Vladislav Rykov's avatar
Vladislav Rykov committed
8
9
10
11
12
13
14
15
16
17
18
19
    cur.execute(
        sql.SQL(
            """CREATE TABLE {} (
                utc NUMERIC(10) NOT NULL,
                timedate VARCHAR(100) NOT NULL,
                data json NOT NULL
            )"""
        ).format(sql.Identifier(tn)))
    return (True,)

    
@with_psql
Vladislav Rykov's avatar
Vladislav Rykov committed
20
21
def delete_table(cur, appkey, devid):
    tn = 'dev_' +str(appkey)+ '_' +str(devid)
Vladislav Rykov's avatar
Vladislav Rykov committed
22
23
24
25
26
27
28
29
    cur.execute(
        psycopg2.sql.SQL(
            "DROP TABLE {}"
        ).format(sql.Identifier(tn)))
    return (True,)


@with_psql
Vladislav Rykov's avatar
Vladislav Rykov committed
30
31
def get_last_n(cur, appkey, devid, n):
    tn = 'dev_' +str(appkey)+ '_' +str(devid)
Vladislav Rykov's avatar
Vladislav Rykov committed
32
33
34
35
36
37
38
    query = """
        SELECT * FROM 
            {}
        ORDER BY 
            utc DESC
        LIMIT %s
        """
Vladislav Rykov's avatar
Vladislav Rykov committed
39
40
41
    cur.execute(
        sql.SQL(query).format(sql.Identifier(tn)), [n])
    data = cur.fetchall()
Vladislav Rykov's avatar
Vladislav Rykov committed
42
        
Vladislav Rykov's avatar
Vladislav Rykov committed
43
44
45
46
    if (data == []):
        return (False, 'There is no data for the device.')
    else:
        return (True, data)
Vladislav Rykov's avatar
Vladislav Rykov committed
47
48
49
50


@with_psql
def get_all(cur, appkey, devid):
Vladislav Rykov's avatar
Vladislav Rykov committed
51
52
    tn = 'dev_' +str(appkey)+ '_' +str(devid)
    query = """
Vladislav Rykov's avatar
Vladislav Rykov committed
53
54
55
        SELECT * FROM
            {}
        """
Vladislav Rykov's avatar
Vladislav Rykov committed
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
    cur.execute(
        sql.SQL(query).format(sql.Identifier(tn)))
    return (True, cur.fetchall())

@with_psql
def get_count(cur, appkey, devid):
    tn = 'dev_' +str(appkey)+ '_' +str(devid)
    query = """
        SELECT COUNT(utc) FROM
            {}
        """
    cur.execute(
        sql.SQL(query).format(sql.Identifier(tn)))
    return (True, cur.fetchone())

Vladislav Rykov's avatar
Vladislav Rykov committed
71