aboutsummaryrefslogtreecommitdiff
path: root/app/db.py
blob: 17504726e6b2cfa4b70f4336536c457c4c8f3265 (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
import sqlalchemy
import os

try:
    os.mkdir('data')
except FileExistsError:
    pass
engine = sqlalchemy.create_engine('sqlite:///data/data.db')


def init_db():
    with engine.begin() as conn:
        conn.execute(sqlalchemy.text(
            '''
            CREATE TABLE IF NOT EXISTS keys (
                api_key, PRIMARY KEY (api_key)
            )
            '''
        ))
        conn.execute(sqlalchemy.text(
            '''
            CREATE TABLE IF NOT EXISTS links (
                owner, link, redirect_link, expire_date,
                FOREIGN KEY (owner) REFERENCES keys(api_key), PRIMARY KEY (link)
            )
            '''
        ))
        conn.execute(sqlalchemy.text(
            '''
            CREATE TABLE IF NOT EXISTS records (
                owner, link, timestamp, ip, location, browser, os, user_agent, isp,
                FOREIGN KEY (owner) REFERENCES links(owner),
                FOREIGN KEY (link) REFERENCES links(link))
            '''
        ))

        conn.commit()