Skip to content

Commit a89425f

Browse files
committed
Support SQLite versions without upsert
Signed-off-by: Aarni Koskela <akx@iki.fi>
1 parent 570df71 commit a89425f

File tree

1 file changed

+31
-10
lines changed

1 file changed

+31
-10
lines changed

prometheus_client/multiprocess/sqlite.py

Lines changed: 31 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,9 @@
77
import os
88
import sqlite3
99

10+
# "UPSERT syntax was added to SQLite with version 3.24.0 (2018-06-04)."
11+
has_upsert = (sqlite3.sqlite_version_info[:2] >= (3, 24))
12+
1013

1114
def sqlite_key(metric_name, name, labelnames, labelvalues, type, multiprocess_mode):
1215
"""Format a key for use in the SQLite file."""
@@ -99,19 +102,37 @@ def __init__(self, typ, metric_name, name, labelnames, labelvalues, multiprocess
99102

100103
def inc(self, amount):
101104
pid = self.pid_func()
102-
self.database.execute(
103-
'INSERT INTO prom_values (pid, muid, m_key, multiprocess_mode, value) VALUES (?, ?, ?, ?, ?) '
104-
'ON CONFLICT (pid, muid) DO UPDATE SET value = value + ?',
105-
(pid, self._muid, self._key, self.multiprocess_mode, amount, amount)
106-
)
105+
if has_upsert:
106+
self.database.execute(
107+
'INSERT INTO prom_values (pid, muid, m_key, multiprocess_mode, value) '
108+
'VALUES (?, ?, ?, ?, ?) '
109+
'ON CONFLICT (pid, muid) DO UPDATE SET value = value + ?',
110+
(pid, self._muid, self._key, self.multiprocess_mode, amount, amount)
111+
)
112+
else:
113+
# This is not 100% atomic.
114+
cur = self.database.execute(
115+
'UPDATE prom_values SET value = value + ? WHERE pid = ? AND muid = ?',
116+
(amount, pid, self._muid)
117+
)
118+
if not cur.rowcount:
119+
self.set(amount)
107120

108121
def set(self, value):
109122
pid = self.pid_func()
110-
self.database.execute(
111-
'INSERT INTO prom_values (pid, muid, m_key, multiprocess_mode, value) VALUES (?, ?, ?, ?, ?) '
112-
'ON CONFLICT (pid, muid) DO UPDATE SET value = ?',
113-
(pid, self._muid, self._key, self.multiprocess_mode, value, value)
114-
)
123+
if has_upsert:
124+
self.database.execute(
125+
'INSERT INTO prom_values (pid, muid, m_key, multiprocess_mode, value) '
126+
'VALUES (?, ?, ?, ?, ?) '
127+
'ON CONFLICT (pid, muid) DO UPDATE SET value = ?',
128+
(pid, self._muid, self._key, self.multiprocess_mode, value, value)
129+
)
130+
else:
131+
self.database.execute(
132+
'INSERT OR REPLACE INTO prom_values (pid, muid, m_key, multiprocess_mode, value) '
133+
'VALUES (?, ?, ?, ?, ?)',
134+
(pid, self._muid, self._key, self.multiprocess_mode, value)
135+
)
115136

116137
def get(self):
117138
pid = self.pid_func()

0 commit comments

Comments
 (0)