aboutsummaryrefslogtreecommitdiffstats
path: root/paste/store.py
blob: 26643cf463a28f591f589de59acb9386d92dd67e (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
from sqlite3 import Connection


def put(conn: Connection, name: str, content: bytes, content_type: str):
    with conn:
        conn.execute(
            "INSERT OR IGNORE INTO file (content) VALUES (?)",
            (content,),
        )
        conn.execute(
            """
            INSERT INTO link (
                name, content_type, file_hash
            ) VALUES (?, ?, DATA_HASH(?))
            ON CONFLICT DO UPDATE
            SET
                content_type = excluded.content_type,
                file_hash = excluded.file_hash""",
            (name, content_type, content),
        )


def get(conn: Connection, name: str):
    row = conn.execute(
        """SELECT link.content_type, file.hash, file.content
        FROM link
        JOIN file ON file.hash = link.file_hash
        WHERE name_hash = DATA_HASH(?)""",
        (name,),
    ).fetchone()
    return row


def head(conn: Connection, name: str):
    row = conn.execute(
        """SELECT link.content_type, file.hash, length(file.content),
                  CASE
                    WHEN link.content_type LIKE 'text/x.redirect%'
                    THEN file.content
                    ELSE NULL
                  END
        FROM link
        JOIN file ON file.hash = link.file_hash
        WHERE name_hash = DATA_HASH(?)""",
        (name,),
    ).fetchone()
    return row


def delete(conn: Connection, name: str):
    with conn:
        conn.execute("DELETE FROM link WHERE name_hash = DATA_HASH(?)", (name,))