-
Notifications
You must be signed in to change notification settings - Fork 0
/
upsert-postgresql.html
295 lines (247 loc) · 19.8 KB
/
upsert-postgresql.html
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="HandheldFriendly" content="True" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="robots" content="index, follow" />
<link href="https://fonts.googleapis.com/css2?family=Source+Code+Pro:ital,wght@0,400;0,700;1,400&family=Source+Sans+Pro:ital,wght@0,300;0,400;0,700;1,400&display=swap" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="https://dotmobo.xyz/theme/stylesheet/style.min.css">
<link id="dark-theme-style" rel="stylesheet" type="text/css"
media="(prefers-color-scheme: dark), (prefers-color-scheme: no-preference)"
href="https://dotmobo.xyz/theme/stylesheet/dark-theme.min.css">
<link id="pygments-dark-theme" rel="stylesheet" type="text/css"
media="(prefers-color-scheme: dark), (prefers-color-scheme: no-preference)"
href="https://dotmobo.xyz/theme/pygments/monokai.min.css">
<link id="pygments-light-theme" rel="stylesheet" type="text/css"
media="(prefers-color-scheme: light)"
href="https://dotmobo.xyz/theme/pygments/emacs.min.css">
<link rel="stylesheet" type="text/css" href="https://dotmobo.xyz/theme/font-awesome/css/fontawesome.css">
<link rel="stylesheet" type="text/css" href="https://dotmobo.xyz/theme/font-awesome/css/brands.css">
<link rel="stylesheet" type="text/css" href="https://dotmobo.xyz/theme/font-awesome/css/solid.css">
<link href="https://dotmobo.xyz/css/custom.css" rel="stylesheet">
<!-- Google Analytics -->
<script type="text/javascript">
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-68852219-1', 'auto');
ga('send', 'pageview');
</script>
<!-- End Google Analytics -->
<!-- Chrome, Firefox OS and Opera -->
<meta name="theme-color" content="#333333">
<!-- Windows Phone -->
<meta name="msapplication-navbutton-color" content="#333333">
<!-- iOS Safari -->
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
<!-- Microsoft EDGE -->
<meta name="msapplication-TileColor" content="#333333">
<meta name="author" content="Morgan" />
<meta name="description" content="Upsert avec Postgresql" />
<meta name="keywords" content="base de données, postgres, psql, postgresql">
<meta property="og:site_name" content=".mobo"/>
<meta property="og:title" content="Upsert avec Postgresql"/>
<meta property="og:description" content="Upsert avec Postgresql"/>
<meta property="og:locale" content="fr_FR"/>
<meta property="og:url" content="https://dotmobo.xyz/upsert-postgresql.html"/>
<meta property="og:type" content="article"/>
<meta property="article:published_time" content="2015-11-22 00:00:00+01:00"/>
<meta property="article:modified_time" content=""/>
<meta property="article:author" content="https://dotmobo.xyz/author/morgan.html">
<meta property="article:section" content="Postgresql"/>
<meta property="article:tag" content="base de données"/>
<meta property="article:tag" content="postgres"/>
<meta property="article:tag" content="psql"/>
<meta property="article:tag" content="postgresql"/>
<meta property="og:image" content="//dotmobo.xyz/images/avatar700.jpg">
<title>.mobo – Upsert avec Postgresql</title>
</head>
<body >
<aside>
<div>
<a href="https://dotmobo.xyz">
<img src="//dotmobo.xyz/images/avatar700.jpg" alt=".mobo" title=".mobo">
</a>
<h1>
<a href="https://dotmobo.xyz">.mobo</a>
</h1>
<p>Explorations d'un développeur</p>
<ul class="social">
<li>
<a class="sc-github" href="https://github.com/dotmobo" target="_blank">
<i class="fab fa-github"></i>
</a>
</li>
<li>
<a class="sc-twitter" href="https://twitter.com/dotmobo" target="_blank">
<i class="fab fa-twitter"></i>
</a>
</li>
<li>
<a class="sc-rss" href="//dotmobo.xyz/feeds/all.atom.xml" target="_blank">
<i class="fas fa-rss"></i>
</a>
</li>
</ul>
</div>
</aside>
<main>
<nav>
<a href="https://dotmobo.xyz">Accueil</a>
<a href="/categories.html">Catégories</a>
<a href="/tags.html">Tags</a>
<a href="/archives.html">Archives</a>
</nav>
<article class="single">
<header>
<h1 id="upsert-postgresql">Upsert avec Postgresql</h1>
<p>
Posté le 22/11/2015 dans <a href="https://dotmobo.xyz/category/postgresql.html">Postgresql</a>
</p>
</header>
<div>
<img alt="Postgresql" class="align-right" src="./images/postgresql.png" />
<p>Lorsque l'on commence à <a class="reference external" href="http://dotmobo.xyz/introduction-asyncio.html">s'amuser avec asyncio</a>
pour faire des traitements asynchrones sur une base <a class="reference external" href="http://www.postgresqlfr.org/">postgresql</a>
avec <a class="reference external" href="https://github.com/aio-libs/aiopg">aiopg</a>, on rencontre assez vite le problème des accès concurrents
à une ressource partagée.</p>
<p>Et notamment lorsqu'il s'agit d'appliquer de multiples <em>insert</em> ou <em>update</em>, appelés <em>upsert</em> dans le monde de <em>mongodb</em>.</p>
<p>Sous <em>mongodb</em> avec <a class="reference external" href="https://api.mongodb.org/python/current/">pymongo</a> c'est facile,
il suffit de passer le paramètre <em>upsert=True</em> à la méthode <em>update_one</em> :</p>
<div class="highlight"><pre><span></span><span class="o">>></span> <span class="kn">from</span> <span class="nn">pymongo</span> <span class="kn">import</span> <span class="n">MongoClient</span>
<span class="o">>></span> <span class="n">client</span> <span class="o">=</span> <span class="n">MongoClient</span><span class="p">()</span>
<span class="o">>></span> <span class="n">db</span> <span class="o">=</span> <span class="n">client</span><span class="o">.</span><span class="n">test_database</span>
<span class="o">>></span> <span class="n">db</span><span class="o">.</span><span class="n">test</span><span class="o">.</span><span class="n">update_one</span><span class="p">({</span><span class="s1">'x'</span><span class="p">:</span> <span class="mi">1</span><span class="p">},</span> <span class="p">{</span><span class="s1">'$inc'</span><span class="p">:</span> <span class="p">{</span><span class="s1">'x'</span><span class="p">:</span> <span class="mi">3</span><span class="p">}},</span> <span class="n">upsert</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
</pre></div>
<p>Mais sous <em>posgresql</em>, il n'existe pas de mot-clé <em>upsert</em>. Et c'est là que tu te demandes:</p>
<p><em>"Comment faire un upsert en postgresql, tout en évitant les problèmes d'accès concurrents ?"</em></p>
<p>Si tu n'es pas pressé, attends la sortie de postgresql 9.5 qui va inclure <a class="reference external" href="https://wiki.postgresql.org/wiki/What's_new_in_PostgreSQL_9.5#INSERT_..._ON_CONFLICT_DO_NOTHING.2FUPDATE_.28.22UPSERT.22.29">la syntaxe du upsert</a>.</p>
<p>En imaginant une table qui ressemble à ça:</p>
<div class="highlight"><pre><span></span><span class="k">SELECT</span><span class="w"> </span><span class="n">username</span><span class="p">,</span><span class="w"> </span><span class="n">logins</span><span class="w"> </span><span class="k">FROM</span><span class="w"> </span><span class="n">user_logins</span><span class="p">;</span>
<span class="n">username</span><span class="w"> </span><span class="o">|</span><span class="w"> </span><span class="n">logins</span>
<span class="c1">----------+--------</span>
<span class="n">James</span><span class="w"> </span><span class="o">|</span><span class="w"> </span><span class="mi">4</span>
<span class="n">Lois</span><span class="w"> </span><span class="o">|</span><span class="w"> </span><span class="mi">2</span>
<span class="p">(</span><span class="mi">2</span><span class="w"> </span><span class="k">rows</span><span class="p">)</span>
</pre></div>
<p>Et que tu veuilles ajouter deux nouveaux <em>logins</em>:</p>
<div class="highlight"><pre><span></span><span class="k">INSERT</span><span class="w"> </span><span class="k">INTO</span><span class="w"> </span><span class="n">user_logins</span><span class="w"> </span><span class="p">(</span><span class="n">username</span><span class="p">,</span><span class="w"> </span><span class="n">logins</span><span class="p">)</span>
<span class="k">VALUES</span><span class="w"> </span><span class="p">(</span><span class="s1">'Naomi'</span><span class="p">,</span><span class="mi">1</span><span class="p">),(</span><span class="s1">'James'</span><span class="p">,</span><span class="mi">1</span><span class="p">);</span>
</pre></div>
<p>En temps normal, tu auras cette erreur si le <em>username</em> existe déjà en base:</p>
<div class="highlight"><pre><span></span><span class="n">ERROR</span><span class="p">:</span><span class="w"> </span><span class="n">duplicate</span><span class="w"> </span><span class="k">key</span><span class="w"> </span><span class="n">value</span><span class="w"> </span><span class="n">violates</span><span class="w"> </span><span class="k">unique</span><span class="w"> </span><span class="k">constraint</span><span class="w"> </span><span class="ss">"users_pkey"</span>
<span class="n">DETAIL</span><span class="p">:</span><span class="w"> </span><span class="k">Key</span><span class="w"> </span><span class="p">(</span><span class="n">username</span><span class="p">)</span><span class="o">=</span><span class="p">(</span><span class="n">James</span><span class="p">)</span><span class="w"> </span><span class="n">already</span><span class="w"> </span><span class="k">exists</span><span class="p">.</span>
</pre></div>
<p>Et bien en 9.5, tu pourras gérer ça de cette manière:</p>
<div class="highlight"><pre><span></span><span class="k">INSERT</span><span class="w"> </span><span class="k">INTO</span><span class="w"> </span><span class="n">user_logins</span><span class="w"> </span><span class="p">(</span><span class="n">username</span><span class="p">,</span><span class="w"> </span><span class="n">logins</span><span class="p">)</span>
<span class="k">VALUES</span><span class="w"> </span><span class="p">(</span><span class="s1">'Naomi'</span><span class="p">,</span><span class="mi">1</span><span class="p">),(</span><span class="s1">'James'</span><span class="p">,</span><span class="mi">1</span><span class="p">)</span>
<span class="k">ON</span><span class="w"> </span><span class="n">CONFLICT</span><span class="w"> </span><span class="p">(</span><span class="n">username</span><span class="p">)</span>
<span class="k">DO</span><span class="w"> </span><span class="k">UPDATE</span><span class="w"> </span><span class="k">SET</span><span class="w"> </span><span class="n">logins</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">user_logins</span><span class="p">.</span><span class="n">logins</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="n">EXCLUDED</span><span class="p">.</span><span class="n">logins</span><span class="p">;</span>
</pre></div>
<p>Génial non ?</p>
<p><em>"Oui mais bon, de mon côté, en production, j'ai du postgresql 9.4 et c'est pas près de changer."</em></p>
<p>Dans ce cas-là, je t'invite à lire <a class="reference external" href="http://www.depesz.com/2012/06/10/why-is-upsert-so-complicated/">ce très bon article</a>
qui date un peu, mais qui résume très bien la situation.</p>
<p>Pour rester simple, l'idée est d'effectuer un <em>update</em> si l'entrée existe déjà ou un <em>insert</em> sinon.
Mais lors d'accès concurrents, il se peut très bien que l'entrée ait été ajoutée par un autre processus entre
ta tentative ratée d'<em>update</em> et ton <em>insert</em> qui suit. Et là, ça plante lamentablement.</p>
<p>Alors oui, il existe les <em>locks</em> et les transactions, mais çe n'est pas suffisant et ça peut poser certains problèmes.
Par exemple, <em>postgresql</em> stoppe une transaction en cours lorsqu'il rencontre une erreur.
Pour plus de détail, lis l'article que j'ai cité précédemment.</p>
<p>Du coup, la <a class="reference external" href="http://stackoverflow.com/questions/1109061/insert-on-duplicate-update-in-postgresql?answertab=votes#tab-top">solution admise par la communauté stackoverflow</a>
est la suivante. Tu écris une fonction <a class="reference external" href="https://fr.wikipedia.org/wiki/PL/SQL">pl/sql</a> qui boucle sur le <em>update</em> ou <em>insert</em>, en utilisant l'exception <em>unique_violation</em>.
Du coup, cette fonction s'appelle à l'aide d'un seul <em>select</em>, donc pas besoin de <em>lock</em> ou de transaction:</p>
<div class="highlight"><pre><span></span><span class="k">CREATE</span><span class="w"> </span><span class="k">TABLE</span><span class="w"> </span><span class="n">db</span><span class="w"> </span><span class="p">(</span><span class="n">a</span><span class="w"> </span><span class="nb">INT</span><span class="w"> </span><span class="k">PRIMARY</span><span class="w"> </span><span class="k">KEY</span><span class="p">,</span><span class="w"> </span><span class="n">b</span><span class="w"> </span><span class="nb">TEXT</span><span class="p">);</span>
<span class="k">CREATE</span><span class="w"> </span><span class="k">FUNCTION</span><span class="w"> </span><span class="n">merge_db</span><span class="p">(</span><span class="k">key</span><span class="w"> </span><span class="nb">INT</span><span class="p">,</span><span class="w"> </span><span class="k">data</span><span class="w"> </span><span class="nb">TEXT</span><span class="p">)</span><span class="w"> </span><span class="k">RETURNS</span><span class="w"> </span><span class="n">VOID</span><span class="w"> </span><span class="k">AS</span>
<span class="err">$$</span>
<span class="k">BEGIN</span>
<span class="w"> </span><span class="n">LOOP</span>
<span class="w"> </span><span class="c1">-- first try to update the key</span>
<span class="w"> </span><span class="c1">-- note that "a" must be unique</span>
<span class="w"> </span><span class="k">UPDATE</span><span class="w"> </span><span class="n">db</span><span class="w"> </span><span class="k">SET</span><span class="w"> </span><span class="n">b</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="k">data</span><span class="w"> </span><span class="k">WHERE</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="k">key</span><span class="p">;</span>
<span class="w"> </span><span class="k">IF</span><span class="w"> </span><span class="k">found</span><span class="w"> </span><span class="k">THEN</span>
<span class="w"> </span><span class="k">RETURN</span><span class="p">;</span>
<span class="w"> </span><span class="k">END</span><span class="w"> </span><span class="k">IF</span><span class="p">;</span>
<span class="w"> </span><span class="c1">-- not there, so try to insert the key</span>
<span class="w"> </span><span class="c1">-- if someone else inserts the same key concurrently,</span>
<span class="w"> </span><span class="c1">-- we could get a unique-key failure</span>
<span class="w"> </span><span class="k">BEGIN</span>
<span class="w"> </span><span class="k">INSERT</span><span class="w"> </span><span class="k">INTO</span><span class="w"> </span><span class="n">db</span><span class="p">(</span><span class="n">a</span><span class="p">,</span><span class="n">b</span><span class="p">)</span><span class="w"> </span><span class="k">VALUES</span><span class="w"> </span><span class="p">(</span><span class="k">key</span><span class="p">,</span><span class="w"> </span><span class="k">data</span><span class="p">);</span>
<span class="w"> </span><span class="k">RETURN</span><span class="p">;</span>
<span class="w"> </span><span class="k">EXCEPTION</span><span class="w"> </span><span class="k">WHEN</span><span class="w"> </span><span class="n">unique_violation</span><span class="w"> </span><span class="k">THEN</span>
<span class="w"> </span><span class="c1">-- do nothing, and loop to try the UPDATE again</span>
<span class="w"> </span><span class="k">END</span><span class="p">;</span>
<span class="w"> </span><span class="k">END</span><span class="w"> </span><span class="n">LOOP</span><span class="p">;</span>
<span class="k">END</span><span class="p">;</span>
<span class="err">$$</span>
<span class="k">LANGUAGE</span><span class="w"> </span><span class="n">plpgsql</span><span class="p">;</span>
<span class="k">SELECT</span><span class="w"> </span><span class="n">merge_db</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span><span class="w"> </span><span class="s1">'david'</span><span class="p">);</span>
<span class="k">SELECT</span><span class="w"> </span><span class="n">merge_db</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span><span class="w"> </span><span class="s1">'dennis'</span><span class="p">);</span>
</pre></div>
</div>
<div class="tag-cloud">
<p>
<a href="https://dotmobo.xyz/tag/base-de-donnees.html">base de données</a>
<a href="https://dotmobo.xyz/tag/postgres.html">postgres</a>
<a href="https://dotmobo.xyz/tag/psql.html">psql</a>
<a href="https://dotmobo.xyz/tag/postgresql.html">postgresql</a>
</p>
</div>
<!-- Disqus -->
<div id="disqus_thread"></div>
<script type="text/javascript">
var disqus_shortname = 'dotmobo';
(function() {
var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
})();
</script>
<noscript>
Veuillez activer le JavaScript pour voir les commentaires.
</noscript>
<!-- End Disqus -->
</article>
<footer>
<p>
© 2024 - This work is licensed under a <a rel="license" href="http://creativecommons.org/licenses/by-sa/4.0/">Creative Commons Attribution-ShareAlike 4.0 International License</a>
</p>
<p>
Construit avec <a href="http://getpelican.com" target="_blank">Pelican</a> utilisant le thème <a href="http://bit.ly/flex-pelican" target="_blank">Flex</a>
<span class="footer-separator">|</span>
Switch to the <a href="javascript:void(0)" onclick="theme.switch(`dark`)">dark</a> | <a href="javascript:void(0)" onclick="theme.switch(`light`)">light</a> | <a href="javascript:void(0)" onclick="theme.switch(`browser`)">browser</a> theme
<script id="dark-theme-script"
src="https://dotmobo.xyz/theme/dark-theme/dark-theme.min.js"
data-enable-auto-detect-theme="True"
data-default-theme="dark"
type="text/javascript">
</script>
</p><p>
<a rel="license"
href="http://creativecommons.org/licenses/by-sa/4.0/"
target="_blank">
<img alt="Creative Commons License"
title="Creative Commons License"
style="border-width:0"
src="https://i.creativecommons.org/l/by-sa/4.0/80x15.png"
width="80"
height="15"/>
</a>
</p> </footer>
</main>
<script type="application/ld+json">
{
"@context" : "http://schema.org",
"@type" : "Blog",
"name": " .mobo ",
"url" : "https://dotmobo.xyz",
"image": "//dotmobo.xyz/images/avatar700.jpg",
"description": ".mobo - explorations d'un développeur"
}
</script>
</body>
</html>