aboutsummaryrefslogtreecommitdiffstats
path: root/paste/store.py
blob: dd00eddc990ec73dd0b8ab42ceed48fe83402030 (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
from secrets import token_urlsafe
from sqlite3 import Connection, IntegrityError


def put(conn: Connection, name: str, content: bytes, content_type: str):
    with conn:
        conn.execute(
            "INSERT OR IGNORE INTO file (content) VALUES (?)",
            (content,),
        )
        (content_hash,) = conn.execute("SELECT DATA_HASH(?)", (content,)).fetchone()
        cur = conn.execute(
            """UPDATE link
            SET content_type = ?, file_hash = ?
            WHERE name_hash = DATA_HASH(?)""",
            (content_type, content_hash, name),
        )
        if cur.rowcount == 1:
            return False, content_hash
        conn.execute(
            """INSERT INTO link (
                name, content_type, file_hash
            ) VALUES (?, ?, ?)""",
            (name, content_type, content_hash),
        )
        return True, content_hash


def post(conn: Connection, prefix: str, content: bytes, content_type: str):
    with conn:
        conn.execute(
            "INSERT OR IGNORE INTO file (content) VALUES (?)",
            (content,),
        )
        (content_hash,) = conn.execute("SELECT DATA_HASH(?)", (content,)).fetchone()
        for _ in range(16):
            name = prefix + token_urlsafe(5)
            try:
                conn.execute(
                    """INSERT INTO link (name, content_type, file_hash)
                        VALUES (?, ?, ?)""",
                    (name, content_type, content_hash),
                )
            except IntegrityError:
                continue
            break
        else:
            raise RuntimeError("Could not insert a link in 16 attempts")
        return name, content_hash


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)
        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:
        cur = conn.execute("DELETE FROM link WHERE name_hash = DATA_HASH(?)", (name,))
        return cur.rowcount == 1