|
7 | 7 | import os |
8 | 8 | import sqlite3 |
9 | 9 |
|
| 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 | + |
10 | 13 |
|
11 | 14 | def sqlite_key(metric_name, name, labelnames, labelvalues, type, multiprocess_mode): |
12 | 15 | """Format a key for use in the SQLite file.""" |
@@ -99,19 +102,37 @@ def __init__(self, typ, metric_name, name, labelnames, labelvalues, multiprocess |
99 | 102 |
|
100 | 103 | def inc(self, amount): |
101 | 104 | 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) |
107 | 120 |
|
108 | 121 | def set(self, value): |
109 | 122 | 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 | + ) |
115 | 136 |
|
116 | 137 | def get(self): |
117 | 138 | pid = self.pid_func() |
|
0 commit comments