-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patharticles.xml
More file actions
3800 lines (3694 loc) · 465 KB
/
Copy patharticles.xml
File metadata and controls
3800 lines (3694 loc) · 465 KB
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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom"><title>Articles</title><link href="https://www.psycopg.org/articles/" rel="alternate"/><link href="https://www.psycopg.org/articles.xml" rel="self"/><id>urn:uuid:1f583092-c4bb-3a77-9f6f-c8ac41335aab</id><updated>2026-06-24T00:00:00Z</updated><author><name/></author><entry><title>Integrating Psycopg with FastAPI and Pydantic</title><link href="https://www.psycopg.org/articles/2026/06/24/pydantic-fastapi/" rel="alternate"/><updated>2026-06-24T00:00:00Z</updated><author><name>Daniele Varrazzo</name></author><id>urn:uuid:eaec8456-6be7-3dc7-bd65-e65620e74b08</id><content type="html"><p><a class="reference external" href="https://fastapi.tiangolo.com/">FastAPI</a> is currently the established
framework to write a REST API in Python. Its clever use of dependency
injections and static typing makes developing web services a breeze, using a
minimal amount of code and a clean and consistent architecture.</p>
<!-- CUT-HERE -->
<p>It's not difficult to see why. A minimal working server, serving a list and
the details of a set of people, is the following:</p>
<pre class="code python literal-block">
<span class="kn">from</span><span class="w"> </span><span class="nn">fastapi</span><span class="w"> </span><span class="kn">import</span> <span class="n">FastAPI</span><span class="w">
</span><span class="n">app</span> <span class="o">=</span> <span class="n">FastAPI</span><span class="p">(</span><span class="n">title</span><span class="o">=</span><span class="s2">&quot;My People&quot;</span><span class="p">)</span><span class="w">
</span><span class="nd">&#64;app</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s2">&quot;/person&quot;</span><span class="p">)</span><span class="w">
</span><span class="k">def</span><span class="w"> </span><span class="nf">list_people</span><span class="p">():</span><span class="w">
</span> <span class="k">return</span> <span class="p">[]</span><span class="w">
</span><span class="nd">&#64;app</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s2">&quot;/person/</span><span class="si">{id}</span><span class="s2">&quot;</span><span class="p">)</span><span class="w">
</span><span class="k">def</span><span class="w"> </span><span class="nf">get_person</span><span class="p">(</span><span class="nb">id</span><span class="p">):</span><span class="w">
</span> <span class="k">return</span> <span class="p">{</span><span class="s2">&quot;id&quot;</span><span class="p">:</span> <span class="nb">id</span><span class="p">}</span>
</pre>
<p>Just <tt class="docutils literal">pip install 'fastapi[standard]'</tt>, save the above script in a
<tt class="docutils literal">server.py</tt> file, and run it with <tt class="docutils literal">fastapi dev server.py</tt>: this will bring
up a development server serving your API on port 8000:</p>
<pre class="code sh literal-block">
$<span class="w"> </span>curl<span class="w"> </span>-s<span class="w"> </span>http://localhost:8000/person<span class="w">
</span><span class="o">[]</span><span class="w">
</span>$<span class="w"> </span>curl<span class="w"> </span>-s<span class="w"> </span>http://localhost:8000/person/123<span class="w">
</span><span class="o">{</span><span class="s2">&quot;id&quot;</span>:<span class="s2">&quot;123&quot;</span><span class="o">}</span>
</pre>
<p>Furthermore you can point your browser to <a class="reference external" href="http://localhost:8000/docs">http://localhost:8000/docs</a> and
you will be served a <a class="reference external" href="https://swagger.io/">Swagger</a> web interface allowing
you to interact with the API:</p>
<div class="figure">
<img alt="swagger-1.png" src="swagger-1.png" />
</div>
<p>That's already quite some infrastructure in place! However it doesn't specify
anything about our model. What does a <em>Person</em> look like? This is where
Pydantic comes into play.</p>
<div class="section" id="enter-pydantic">
<h2>Enter Pydantic</h2>
<p><a class="reference external" href="https://pydantic.dev/docs/validation/latest/get-started/">Pydantic</a> lets you
define an object's attributes, validate them, and describe them, just using
<a class="reference external" href="https://typing.python.org/en/latest/spec/annotations.html">Python type annotations</a>.</p>
<p>Let's say that our person will have a name (mandatory) and a date of birth
(which we allow to be nullable because we might not know it). We will also
want an id on the record - let's say it will be a UUID. This definition can
be represented with:</p>
<pre class="code python literal-block">
<span class="kn">import</span><span class="w"> </span><span class="nn">datetime</span><span class="w"> </span><span class="k">as</span><span class="w"> </span><span class="nn">dt</span><span class="w">
</span><span class="kn">from</span><span class="w"> </span><span class="nn">uuid</span><span class="w"> </span><span class="kn">import</span> <span class="n">UUID</span><span class="p">,</span> <span class="n">uuid4</span><span class="w">
</span><span class="kn">from</span><span class="w"> </span><span class="nn">pydantic</span><span class="w"> </span><span class="kn">import</span> <span class="n">BaseModel</span><span class="p">,</span> <span class="n">Field</span><span class="w">
</span><span class="k">class</span><span class="w"> </span><span class="nc">Person</span><span class="p">(</span><span class="n">BaseModel</span><span class="p">):</span><span class="w">
</span> <span class="nb">id</span><span class="p">:</span> <span class="n">UUID</span> <span class="o">=</span> <span class="n">Field</span><span class="p">(</span><span class="n">default_factory</span><span class="o">=</span><span class="n">uuid4</span><span class="p">)</span><span class="w">
</span> <span class="n">name</span><span class="p">:</span> <span class="nb">str</span><span class="w">
</span> <span class="n">date_of_birth</span><span class="p">:</span> <span class="n">dt</span><span class="o">.</span><span class="n">date</span> <span class="o">|</span> <span class="kc">None</span> <span class="o">=</span> <span class="kc">None</span>
</pre>
<p>This representation is enough to create an object with advanced validation,
arguments conversion and output. In a Python shell we can play with it:</p>
<pre class="code python-console literal-block">
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span> <span class="o">=</span> <span class="n">Person</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s2">&quot;John Doe&quot;</span><span class="p">,</span> <span class="n">date_of_birth</span><span class="o">=</span><span class="s2">&quot;1970-01-01&quot;</span><span class="p">)</span><span class="w">
</span><span class="go">
</span><span class="gp">&gt;&gt;&gt; </span><span class="n">p</span> <span class="c1"># object with attributes converted to the right types</span><span class="w">
</span><span class="go">Person(id=UUID('94d69603-c3f7-4dd4-9d64-eb1a24fc6fed'), name='John Doe', date_of_birth=datetime.date(1970, 1, 1))
</span><span class="gp">&gt;&gt;&gt; </span><span class="n">p</span><span class="o">.</span><span class="n">model_dump</span><span class="p">()</span> <span class="c1"># convert the object to a Python dictionary</span><span class="w">
</span><span class="go">{'id': UUID('94d69603-c3f7-4dd4-9d64-eb1a24fc6fed'),
'name': 'John Doe',
'date_of_birth': datetime.date(1970, 1, 1)}
</span><span class="gp">&gt;&gt;&gt; </span><span class="n">p</span><span class="o">.</span><span class="n">model_dump_json</span><span class="p">()</span> <span class="c1"># convert the object to a JSON string</span><span class="w">
</span><span class="go">'{&quot;id&quot;:&quot;94d69603-c3f7-4dd4-9d64-eb1a24fc6fed&quot;,&quot;name&quot;:&quot;John Doe&quot;,&quot;date_of_birth&quot;:&quot;1970-01-01&quot;}'</span>
</pre>
<p>Now that we have this model we can annotate the views to signify that they
will return a <tt class="docutils literal">Person</tt> object and a list of such objects:</p>
<pre class="code python literal-block">
<span class="nd">&#64;app</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s2">&quot;/person&quot;</span><span class="p">)</span><span class="w">
</span><span class="k">def</span><span class="w"> </span><span class="nf">list_people</span><span class="p">()</span> <span class="o">-&gt;</span> <span class="nb">list</span><span class="p">[</span><span class="n">Person</span><span class="p">]:</span><span class="w">
</span> <span class="k">return</span> <span class="p">[]</span><span class="w">
</span><span class="nd">&#64;app</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s2">&quot;/person/</span><span class="si">{id}</span><span class="s2">&quot;</span><span class="p">)</span><span class="w">
</span><span class="k">def</span><span class="w"> </span><span class="nf">get_person</span><span class="p">(</span><span class="nb">id</span><span class="p">:</span> <span class="n">UUID</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="n">Person</span><span class="p">:</span><span class="w">
</span> <span class="k">return</span> <span class="n">Person</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="nb">id</span><span class="p">,</span> <span class="n">name</span><span class="o">=</span><span class="s2">&quot;John Doe&quot;</span><span class="p">)</span>
</pre>
<p>This is enough to give a pretty representation, from formal definition to
result samples, in the Swagger interface:</p>
<div class="figure">
<img alt="swagger-2.png" src="swagger-2.png" />
</div>
<p>Of course the objects that we are returning are fake and incomplete. The
database knows the truth and it won't come as a surprise that we will want to
use <a class="reference external" href="https://www.psycopg.org/">Psycopg</a> to retrieve it...</p>
</div>
<div class="section" id="connecting-views-and-the-database">
<h2>Connecting views and the database</h2>
<p>Let's create a table for this example and seed it with a couple of test
records:</p>
<pre class="code sql literal-block">
<span class="k">CREATE</span><span class="w"> </span><span class="k">TABLE</span><span class="w"> </span><span class="n">person</span><span class="w"> </span><span class="p">(</span><span class="w">
</span><span class="n">id</span><span class="w"> </span><span class="n">uuid</span><span class="w"> </span><span class="k">PRIMARY</span><span class="w"> </span><span class="k">KEY</span><span class="w"> </span><span class="k">DEFAULT</span><span class="w"> </span><span class="n">gen_random_uuid</span><span class="p">(),</span><span class="w">
</span><span class="n">name</span><span class="w"> </span><span class="nb">text</span><span class="w"> </span><span class="k">NOT</span><span class="w"> </span><span class="k">NULL</span><span class="p">,</span><span class="w">
</span><span class="n">date_of_birth</span><span class="w"> </span><span class="nb">date</span><span class="p">);</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">person</span><span class="w"> </span><span class="p">(</span><span class="n">name</span><span class="p">,</span><span class="w"> </span><span class="n">date_of_birth</span><span class="p">)</span><span class="w">
</span><span class="k">VALUES</span><span class="w"> </span><span class="p">(</span><span class="s1">'Alice'</span><span class="p">,</span><span class="w"> </span><span class="s1">'1970-01-01'</span><span class="p">);</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">person</span><span class="w"> </span><span class="p">(</span><span class="n">name</span><span class="p">,</span><span class="w"> </span><span class="n">date_of_birth</span><span class="p">)</span><span class="w">
</span><span class="k">VALUES</span><span class="w"> </span><span class="p">(</span><span class="s1">'Bob'</span><span class="p">,</span><span class="w"> </span><span class="k">NULL</span><span class="p">);</span>
</pre>
<p>I'll assume that the table is created in the &quot;default database&quot;, the one you
connect to by typing <tt class="docutils literal">psql</tt> with no other argument. If you need to use a
different database you can specify <a class="reference external" href="https://www.postgresql.org/docs/current/libpq-envars.html"><tt class="docutils literal">PG*</tt> env vars</a> to select a different database to
connect to, or hardcode a connection string in the following
examples. Configuring FastAPI is outside the scope of this article (but psst...
check <a class="reference external" href="https://pydantic.dev/docs/validation/latest/concepts/pydantic_settings/">Pydantic Settings</a>).</p>
<p>Creating a working database connection, configuring it correctly, managing its
life cycle, are matters separate from the code of the view functions, which
just <em>require</em> a database connection. FastAPI offers an elegant method to
separate these two independent concerns: the <a class="reference external" href="https://fastapi.tiangolo.com/tutorial/dependencies/">dependency injection</a>.</p>
<p>The first part is creating a <em>dependency</em>: this is simply a function that
creates, and optionally disposes of, an object. The one managing our
connection could be simply:</p>
<pre class="code python literal-block">
<span class="kn">import</span><span class="w"> </span><span class="nn">psycopg</span><span class="w">
</span><span class="k">def</span><span class="w"> </span><span class="nf">get_connection</span><span class="p">():</span><span class="w">
</span> <span class="c1"># Use the PG* env vars to configure the database connection</span><span class="w">
</span> <span class="k">with</span> <span class="n">psycopg</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="s2">&quot;&quot;</span><span class="p">)</span> <span class="k">as</span> <span class="n">conn</span><span class="p">:</span><span class="w">
</span> <span class="k">yield</span> <span class="n">conn</span>
</pre>
<p>Using <tt class="docutils literal">yield</tt> in the context manager will make sure that the connection is
correctly closed when the view function terminates.</p>
<p>Once we have this normal Python function we can define a <em>type alias</em> to
enrich a type (the Psycopg connection) with the metadata defining how to
obtain one (there are other ways, but defining an alias minimises
repetitions):</p>
<pre class="code python literal-block">
<span class="kn">from</span><span class="w"> </span><span class="nn">typing</span><span class="w"> </span><span class="kn">import</span> <span class="n">Annotated</span><span class="w">
</span><span class="n">Conn</span> <span class="o">=</span> <span class="n">Annotated</span><span class="p">[</span><span class="n">psycopg</span><span class="o">.</span><span class="n">Connection</span><span class="p">,</span> <span class="n">Depends</span><span class="p">(</span><span class="n">get_connection</span><span class="p">)]</span>
</pre>
<p>This completes the creation of the dependency. In order to use it, i.e. to
define that the <tt class="docutils literal">get_person()</tt> function requires a database connection to
work, it is sufficient to add an argument of type <tt class="docutils literal">Conn</tt> to the function
definition. In order to reuse code between the two views, we can write a
helper function, <tt class="docutils literal">fetch_people()</tt>, taking an optional <tt class="docutils literal">id</tt> argument
if we want only one, which would run the proper query:</p>
<pre class="code python literal-block">
<span class="kn">from</span><span class="w"> </span><span class="nn">fastapi</span><span class="w"> </span><span class="kn">import</span> <span class="n">HTTPException</span><span class="w">
</span><span class="nd">&#64;app</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s2">&quot;/person&quot;</span><span class="p">)</span><span class="w">
</span><span class="k">def</span><span class="w"> </span><span class="nf">list_people</span><span class="p">(</span><span class="n">conn</span><span class="p">:</span> <span class="n">Conn</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="nb">list</span><span class="p">[</span><span class="n">Person</span><span class="p">]:</span><span class="w">
</span> <span class="k">return</span> <span class="n">fetch_people</span><span class="p">(</span><span class="n">conn</span><span class="p">)</span><span class="w">
</span><span class="nd">&#64;app</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s2">&quot;/person/</span><span class="si">{id}</span><span class="s2">&quot;</span><span class="p">)</span><span class="w">
</span><span class="k">def</span><span class="w"> </span><span class="nf">get_person</span><span class="p">(</span><span class="nb">id</span><span class="p">:</span> <span class="n">UUID</span><span class="p">,</span> <span class="n">conn</span><span class="p">:</span> <span class="n">Conn</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="n">Person</span><span class="p">:</span><span class="w">
</span> <span class="k">if</span> <span class="n">people</span> <span class="o">:=</span> <span class="n">fetch_people</span><span class="p">(</span><span class="n">conn</span><span class="p">,</span> <span class="nb">id</span><span class="o">=</span><span class="nb">id</span><span class="p">):</span><span class="w">
</span> <span class="k">return</span> <span class="n">people</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span><span class="w">
</span> <span class="k">else</span><span class="p">:</span><span class="w">
</span> <span class="k">raise</span> <span class="n">HTTPException</span><span class="p">(</span><span class="n">status_code</span><span class="o">=</span><span class="mi">404</span><span class="p">)</span><span class="w">
</span><span class="k">def</span><span class="w"> </span><span class="nf">fetch_people</span><span class="p">(</span><span class="n">conn</span><span class="p">:</span> <span class="n">psycopg</span><span class="o">.</span><span class="n">Connection</span><span class="p">,</span> <span class="nb">id</span><span class="p">:</span> <span class="n">UUID</span> <span class="o">|</span> <span class="kc">None</span> <span class="o">=</span> <span class="kc">None</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="nb">list</span><span class="p">[</span><span class="n">Person</span><span class="p">]:</span><span class="w">
</span> <span class="c1"># We will implement this later</span><span class="w">
</span> <span class="o">...</span>
</pre>
<p>The views are pretty much just acting as a bridge between the environment (the
FastAPI runtime and how it's configured) and the &quot;business logic&quot; (our
database queries in this case, but there could be much more there). Note that
the views use the <tt class="docutils literal">Conn</tt> alias, so that FastAPI will inject the connection,
whereas <tt class="docutils literal">fetch_people()</tt> just asks for a plain <tt class="docutils literal">psycopg.Connection</tt>: it
doesn't know or care where the connection comes from. This separation also
makes the code testable: you could write unit tests
exercising <tt class="docutils literal">fetch_people()</tt> in isolation from FastAPI, for example using
<a class="reference external" href="https://docs.pytest.org/en/stable/explanation/fixtures.html">PyTest fixtures</a> to create a database connection (your test database is
likely reached differently from a running server's) and test your business
code independently from whether it is used in FastAPI or in a different
environment.</p>
<p>Let's get down to the proper database querying: the way such code might have
been written in <tt class="docutils literal">psycopg2</tt> could be something like:</p>
<pre class="code python literal-block">
<span class="k">def</span><span class="w"> </span><span class="nf">fetch_people</span><span class="p">(</span><span class="n">conn</span><span class="p">:</span> <span class="n">psycopg</span><span class="o">.</span><span class="n">Connection</span><span class="p">,</span> <span class="nb">id</span><span class="p">:</span> <span class="n">UUID</span> <span class="o">|</span> <span class="kc">None</span> <span class="o">=</span> <span class="kc">None</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="nb">list</span><span class="p">[</span><span class="n">Person</span><span class="p">]:</span><span class="w">
</span> <span class="n">query</span> <span class="o">=</span> <span class="s2">&quot;SELECT id, name, date_of_birth FROM person&quot;</span><span class="w">
</span> <span class="k">if</span> <span class="nb">id</span><span class="p">:</span><span class="w">
</span> <span class="n">query</span> <span class="o">+=</span> <span class="s2">&quot; WHERE id = </span><span class="si">%(id)s</span><span class="s2">&quot;</span><span class="w">
</span> <span class="n">people</span> <span class="o">=</span> <span class="p">[]</span><span class="w">
</span> <span class="k">with</span> <span class="n">conn</span><span class="o">.</span><span class="n">cursor</span><span class="p">()</span> <span class="k">as</span> <span class="n">cur</span><span class="p">:</span><span class="w">
</span> <span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="n">query</span><span class="p">,</span> <span class="p">{</span><span class="s2">&quot;id&quot;</span><span class="p">:</span> <span class="nb">id</span><span class="p">})</span><span class="w">
</span> <span class="k">for</span> <span class="n">rec_id</span><span class="p">,</span> <span class="n">name</span><span class="p">,</span> <span class="n">date_of_birth</span> <span class="ow">in</span> <span class="n">cur</span><span class="p">:</span><span class="w">
</span> <span class="n">people</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">Person</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="n">rec_id</span><span class="p">,</span> <span class="n">name</span><span class="o">=</span><span class="n">name</span><span class="p">,</span> <span class="n">date_of_birth</span><span class="o">=</span><span class="n">date_of_birth</span><span class="p">))</span><span class="w">
</span> <span class="k">return</span> <span class="n">people</span>
</pre>
<p>This is a pretty verbose way to transform database records to instances of the
<tt class="docutils literal">Person</tt> class and classes like <tt class="docutils literal">DictCursor</tt> and similar only help
marginally. Psycopg 3 improved records conversion with the introduction of the
<a class="reference external" href="https://www.psycopg.org/psycopg3/docs/advanced/rows.html">row factories</a>,
which allow creating a direct bridge from the query result to the final
objects.</p>
<pre class="code python literal-block">
<span class="kn">from</span><span class="w"> </span><span class="nn">psycopg.rows</span><span class="w"> </span><span class="kn">import</span> <span class="n">class_row</span><span class="w">
</span><span class="k">def</span><span class="w"> </span><span class="nf">fetch_people</span><span class="p">(</span><span class="n">conn</span><span class="p">:</span> <span class="n">psycopg</span><span class="o">.</span><span class="n">Connection</span><span class="p">,</span> <span class="nb">id</span><span class="p">:</span> <span class="n">UUID</span> <span class="o">|</span> <span class="kc">None</span> <span class="o">=</span> <span class="kc">None</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="nb">list</span><span class="p">[</span><span class="n">Person</span><span class="p">]:</span><span class="w">
</span> <span class="n">query</span> <span class="o">=</span> <span class="s2">&quot;SELECT id, name, date_of_birth FROM person&quot;</span><span class="w">
</span> <span class="k">if</span> <span class="nb">id</span><span class="p">:</span><span class="w">
</span> <span class="n">query</span> <span class="o">+=</span> <span class="s2">&quot; WHERE id = </span><span class="si">%(id)s</span><span class="s2">&quot;</span><span class="w">
</span> <span class="k">with</span> <span class="n">conn</span><span class="o">.</span><span class="n">cursor</span><span class="p">(</span><span class="n">row_factory</span><span class="o">=</span><span class="n">class_row</span><span class="p">(</span><span class="n">Person</span><span class="p">))</span> <span class="k">as</span> <span class="n">cur</span><span class="p">:</span><span class="w">
</span> <span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="n">query</span><span class="p">,</span> <span class="p">{</span><span class="s2">&quot;id&quot;</span><span class="p">:</span> <span class="nb">id</span><span class="p">})</span><span class="w">
</span> <span class="k">return</span> <span class="n">cur</span><span class="o">.</span><span class="n">fetchall</span><span class="p">()</span>
</pre>
<p>Note that Psycopg 3 makes ample use of type annotations and <a class="reference external" href="https://typing.python.org/en/latest/reference/generics.html">generic types</a>:
if you use a static checker such as <a class="reference external" href="https://mypy-lang.org/">Mypy</a>, it will be able to infer that
<tt class="docutils literal">cur.fetchall()</tt> returns a list of <tt class="docutils literal">Person</tt> and not a list of tuples,
allowing you to detect a whole class of errors before even running a test.</p>
<p>If you are using Python 3.14, the use of <a class="reference external" href="https://www.psycopg.org/psycopg3/docs/basic/tstrings.html">template strings</a> makes writing
dynamic queries even simpler:</p>
<pre class="code python literal-block">
<span class="k">def</span><span class="w"> </span><span class="nf">fetch_people</span><span class="p">(</span><span class="n">conn</span><span class="p">:</span> <span class="n">psycopg</span><span class="o">.</span><span class="n">Connection</span><span class="p">,</span> <span class="nb">id</span><span class="p">:</span> <span class="n">UUID</span> <span class="o">|</span> <span class="kc">None</span> <span class="o">=</span> <span class="kc">None</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="nb">list</span><span class="p">[</span><span class="n">Person</span><span class="p">]:</span><span class="w">
</span> <span class="n">query</span> <span class="o">=</span> <span class="sa">t</span><span class="s2">&quot;SELECT id, name, date_of_birth FROM person&quot;</span><span class="w">
</span> <span class="k">if</span> <span class="nb">id</span><span class="p">:</span><span class="w">
</span> <span class="n">query</span> <span class="o">+=</span> <span class="sa">t</span><span class="s2">&quot; WHERE id = </span><span class="si">{</span><span class="nb">id</span><span class="si">}</span><span class="s2">&quot;</span><span class="w">
</span> <span class="k">with</span> <span class="n">conn</span><span class="o">.</span><span class="n">cursor</span><span class="p">(</span><span class="n">row_factory</span><span class="o">=</span><span class="n">class_row</span><span class="p">(</span><span class="n">Person</span><span class="p">))</span> <span class="k">as</span> <span class="n">cur</span><span class="p">:</span><span class="w">
</span> <span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="n">query</span><span class="p">)</span><span class="w">
</span> <span class="k">return</span> <span class="n">cur</span><span class="o">.</span><span class="n">fetchall</span><span class="p">()</span>
</pre>
<p>Either implementation completes the code: the API can be tested using the
Swagger interface or <tt class="docutils literal">curl</tt> on the command line:</p>
<pre class="code sh literal-block">
$<span class="w"> </span>curl<span class="w"> </span>-s<span class="w"> </span>http://localhost:8000/person<span class="w"> </span><span class="p">|</span><span class="w"> </span>jq<span class="w">
</span><span class="o">[</span><span class="w">
</span><span class="o">{</span><span class="w">
</span><span class="s2">&quot;id&quot;</span>:<span class="w"> </span><span class="s2">&quot;a0aaa2d4-9fa4-4baf-83ed-a3fe35f051d3&quot;</span>,<span class="w">
</span><span class="s2">&quot;name&quot;</span>:<span class="w"> </span><span class="s2">&quot;Alice&quot;</span>,<span class="w">
</span><span class="s2">&quot;date_of_birth&quot;</span>:<span class="w"> </span><span class="s2">&quot;1970-01-01&quot;</span><span class="w">
</span><span class="o">}</span>,<span class="w">
</span><span class="o">{</span><span class="w">
</span><span class="s2">&quot;id&quot;</span>:<span class="w"> </span><span class="s2">&quot;706c17ea-2214-4482-810f-e6ed1cfab694&quot;</span>,<span class="w">
</span><span class="s2">&quot;name&quot;</span>:<span class="w"> </span><span class="s2">&quot;Bob&quot;</span>,<span class="w">
</span><span class="s2">&quot;date_of_birth&quot;</span>:<span class="w"> </span>null<span class="w">
</span><span class="o">}</span><span class="w">
</span><span class="o">]</span><span class="w">
</span>$<span class="w"> </span>curl<span class="w"> </span>-s<span class="w"> </span>http://localhost:8000/person/a0aaa2d4-9fa4-4baf-83ed-a3fe35f051d3<span class="w"> </span><span class="p">|</span><span class="w"> </span>jq<span class="w">
</span><span class="o">{</span><span class="w">
</span><span class="s2">&quot;id&quot;</span>:<span class="w"> </span><span class="s2">&quot;a0aaa2d4-9fa4-4baf-83ed-a3fe35f051d3&quot;</span>,<span class="w">
</span><span class="s2">&quot;name&quot;</span>:<span class="w"> </span><span class="s2">&quot;Alice&quot;</span>,<span class="w">
</span><span class="s2">&quot;date_of_birth&quot;</span>:<span class="w"> </span><span class="s2">&quot;1970-01-01&quot;</span><span class="w">
</span><span class="o">}</span><span class="w">
</span><span class="c1"># The status code here is 404, not 200
</span>$<span class="w"> </span>curl<span class="w"> </span>-s<span class="w"> </span>http://localhost:8000/person/00000000-0000-0000-0000-000000000000<span class="w"> </span><span class="p">|</span><span class="w"> </span>jq<span class="w">
</span><span class="o">{</span><span class="w">
</span><span class="s2">&quot;detail&quot;</span>:<span class="w"> </span><span class="s2">&quot;Not Found&quot;</span><span class="w">
</span><span class="o">}</span>
</pre>
</div>
<div class="section" id="pools-and-applications">
<h2>Pools and applications</h2>
<p>Creating a new connection at every request is a big performance hit:
connection creation is a relatively slow operation. For this reason Psycopg
makes a <a class="reference external" href="https://www.psycopg.org/psycopg3/docs/advanced/pool.html#connection-pools">connection pool</a> available, with a set of connections ready to be
used. Remember that the Psycopg pool is distributed as a separate package,
therefore you might want to have something like
<tt class="docutils literal">psycopg[binary,pool]</tt> in your dependencies.</p>
<p>In your program you will want to create a single instance of the pool and have
the views using it. Creating a pool as a global variable works, but a much
more refined way to manage the lifetime of the pool is to tie it to the life
cycle of the application: FastAPI will create the pool at application start
and dispose of it cleanly on program exit. This avoids problems such as
partially initialized code or side effects at import time.</p>
<p>What happens at startup and shutdown is controlled by a <tt class="docutils literal">lifespan</tt> function
passed as argument to the <tt class="docutils literal">FastAPI</tt> object. This too uses the single
<tt class="docutils literal">yield</tt> trick to allow suspending the execution and restoring it (to run the
cleanup part) when the end of the application lifetime is reached. We make use
of this function to create a pool adequately configured:</p>
<pre class="code python literal-block">
<span class="kn">from</span><span class="w"> </span><span class="nn">psycopg_pool</span><span class="w"> </span><span class="kn">import</span> <span class="n">ConnectionPool</span><span class="w">
</span><span class="k">def</span><span class="w"> </span><span class="nf">lifespan</span><span class="p">(</span><span class="n">app</span><span class="p">:</span> <span class="n">FastAPI</span><span class="p">):</span><span class="w">
</span> <span class="k">with</span> <span class="n">ConnectionPool</span><span class="p">(</span><span class="s2">&quot;&quot;</span><span class="p">)</span> <span class="k">as</span> <span class="n">pool</span><span class="p">:</span><span class="w">
</span> <span class="n">app</span><span class="o">.</span><span class="n">state</span><span class="o">.</span><span class="n">pool</span> <span class="o">=</span> <span class="n">pool</span><span class="w">
</span> <span class="k">yield</span><span class="w">
</span><span class="c1"># Add the 'lifespan' argument to the existing app</span><span class="w">
</span><span class="n">app</span> <span class="o">=</span> <span class="n">FastAPI</span><span class="p">(</span><span class="n">title</span><span class="o">=</span><span class="s2">&quot;My People&quot;</span><span class="p">,</span> <span class="n">lifespan</span><span class="o">=</span><span class="n">lifespan</span><span class="p">)</span>
</pre>
<p>The pool creates and maintains a configured number of connections and makes
them available to the application code as soon as one is requested. We only
need to change the body of the dependency injection to obtain a connection
from the pool instead of creating a new one, no change to the views. The
FastAPI <tt class="docutils literal">Request</tt> object (which in turn is another dependency injection)
lets us get the object representing the running application so that we can
obtain the pool instance from it:</p>
<pre class="code python literal-block">
<span class="kn">from</span><span class="w"> </span><span class="nn">fastapi</span><span class="w"> </span><span class="kn">import</span> <span class="n">Request</span><span class="w">
</span><span class="k">def</span><span class="w"> </span><span class="nf">get_connection</span><span class="p">(</span><span class="n">request</span><span class="p">:</span> <span class="n">Request</span><span class="p">):</span><span class="w">
</span> <span class="k">with</span> <span class="n">request</span><span class="o">.</span><span class="n">app</span><span class="o">.</span><span class="n">state</span><span class="o">.</span><span class="n">pool</span><span class="o">.</span><span class="n">connection</span><span class="p">()</span> <span class="k">as</span> <span class="n">conn</span><span class="p">:</span><span class="w">
</span> <span class="k">yield</span> <span class="n">conn</span>
</pre>
</div>
<div class="section" id="conclusions">
<h2>Conclusions</h2>
<p>We have taken a quick look at some FastAPI features (views and models
definition, dependency injections, application lifetime), some Psycopg
features (<tt class="docutils literal">PG*</tt> env vars, row factories, connection pool), and how they can
interact together, with the help of Pydantic as an expressive objects model.</p>
<p>The complete and runnable code of the example can be downloaded <a class="reference external" href="https://gist.github.com/dvarrazzo/0edf2b659e59a8a8e2053e0c633087a5">here</a>.</p>
<p>Happy hacking!</p>
</div>
</content></entry><entry><title>Psycopg 3.3 released</title><link href="https://www.psycopg.org/articles/2025/12/01/psycopg-33-released/" rel="alternate"/><updated>2025-12-01T00:00:00Z</updated><author><name>Daniele Varrazzo</name></author><id>urn:uuid:2593b72d-e32e-37db-9fa0-57834bcf9188</id><content type="html"><p>We have released Psycopg 3.3 - and you should be excited about it!</p>
<!-- CUT-HERE -->
<div class="section" id="template-string-queries">
<h2>Template string queries</h2>
<p>This version lets you take advantage of one of the biggest innovation in
Python 3.14: the <a class="reference external" href="https://docs.python.org/3.14/whatsnew/3.14.html#pep-750-template-string-literals">template strings</a>, which allow you to write
<a class="reference external" href="https://www.psycopg.org/psycopg3/docs/basic/tstrings.html">expressive and safe queries</a>.</p>
<p>How does it look? Something like:</p>
<pre class="code python literal-block">
<span class="k">def</span><span class="w"> </span><span class="nf">fetch_person</span><span class="p">(</span><span class="n">conn</span><span class="p">,</span> <span class="n">name</span><span class="p">):</span><span class="w">
</span> <span class="c1"># 'name' will be handled safely: as a server-side parameter or</span><span class="w">
</span> <span class="c1"># correctly quoted and escaped if client-side binding is required</span><span class="w">
</span> <span class="n">cur</span> <span class="o">=</span> <span class="n">conn</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="sa">t</span><span class="s2">&quot;SELECT * FROM people WHERE name = </span><span class="si">{</span><span class="n">name</span><span class="si">}</span><span class="s2">&quot;</span><span class="p">)</span><span class="w">
</span> <span class="k">return</span> <span class="n">cur</span><span class="o">.</span><span class="n">fetchone</span><span class="p">()</span>
</pre>
<p>The syntax is the same as that of <a class="reference external" href="https://docs.python.org/3/tutorial/inputoutput.html#formatted-string-literals">f-strings</a>, introduced back in the
venerable Python 3.6 (perhaps the feature that finally ended Python 2?),
but now paired with the safety and adaptation flexibility of Psycopg 3.
Template strings also help you generate dynamic SQL statements much more
succinctly than with the <a class="reference external" href="https://www.psycopg.org/psycopg3/docs/api/sql.html">psycopg.sql</a> module:</p>
<pre class="code python literal-block">
<span class="k">def</span><span class="w"> </span><span class="nf">delete_something</span><span class="p">(</span><span class="n">conn</span><span class="p">,</span> <span class="n">table_name</span><span class="p">,</span> <span class="n">name</span><span class="p">):</span><span class="w">
</span> <span class="c1"># Mixing client-side query composition with server-side parameters binding</span><span class="w">
</span> <span class="n">conn</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="sa">t</span><span class="s2">&quot;DELETE FROM </span><span class="si">{</span><span class="n">table_name</span><span class="si">:</span><span class="s2">i</span><span class="si">}</span><span class="s2"> WHERE name = </span><span class="si">{</span><span class="n">name</span><span class="si">}</span><span class="s2">&quot;</span><span class="p">)</span><span class="w">
</span> <span class="c1"># Composing non-parametric statements entirely client-side</span><span class="w">
</span> <span class="n">conn</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="sa">t</span><span class="s2">&quot;NOTIFY </span><span class="si">{</span><span class="n">table_name</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="s1">'.deleted'</span><span class="si">:</span><span class="s2">i</span><span class="si">}</span><span class="s2">, </span><span class="si">{</span><span class="n">name</span><span class="si">:</span><span class="s2">l</span><span class="si">}</span><span class="s2">&quot;</span><span class="p">)</span>
</pre>
<p>Check out the complete <a class="reference external" href="https://www.psycopg.org/psycopg3/docs/basic/tstrings.html">t-string support documentation</a> for inspiration!</p>
</div>
<div class="section" id="more-flexible-composite-adaptation">
<h2>More flexible composite adaptation</h2>
<p>Previously, it was only possible to <a class="reference external" href="https://www.psycopg.org/psycopg3/docs/basic/pgtypes.html#adapt-composite">adapt PostgreSQL composites</a> to Python
sequence types with a strict 1:1 mapping to the fields of the database type.</p>
<p>We have now gained extra flexibility: we can customize both how to create
generic Python objects, for example ones only taking keyword arguments, and
how to extract a sequence of fields from the attributes of non-sequence
objects... Dataclasses anyone?</p>
<pre class="code python literal-block">
<span class="kn">from</span><span class="w"> </span><span class="nn">dataclasses</span><span class="w"> </span><span class="kn">import</span> <span class="n">dataclass</span><span class="w">
</span><span class="kn">from</span><span class="w"> </span><span class="nn">psycopg.types.composite</span><span class="w"> </span><span class="kn">import</span> <span class="n">CompositeInfo</span><span class="p">,</span> <span class="n">register_composite</span><span class="w">
</span><span class="nd">&#64;dataclass</span><span class="w">
</span><span class="k">class</span><span class="w"> </span><span class="nc">MiniPerson</span><span class="p">:</span><span class="w">
</span> <span class="n">age</span><span class="p">:</span> <span class="nb">int</span><span class="w">
</span> <span class="n">name</span><span class="p">:</span> <span class="nb">str</span><span class="w">
</span> <span class="n">height</span><span class="p">:</span> <span class="nb">float</span> <span class="o">|</span> <span class="kc">None</span> <span class="o">=</span> <span class="kc">None</span><span class="w">
</span> <span class="nd">&#64;classmethod</span><span class="w">
</span> <span class="k">def</span><span class="w"> </span><span class="nf">from_db</span><span class="p">(</span><span class="bp">cls</span><span class="p">,</span> <span class="n">seq</span><span class="p">,</span> <span class="n">info</span><span class="p">):</span><span class="w">
</span> <span class="k">return</span> <span class="bp">cls</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="n">seq</span><span class="p">[</span><span class="mi">0</span><span class="p">],</span> <span class="n">age</span><span class="o">=</span><span class="n">seq</span><span class="p">[</span><span class="mi">1</span><span class="p">])</span><span class="w">
</span> <span class="k">def</span><span class="w"> </span><span class="nf">to_db</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">info</span><span class="p">):</span><span class="w">
</span> <span class="k">return</span> <span class="p">[</span><span class="bp">self</span><span class="o">.</span><span class="n">name</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">age</span><span class="p">]</span><span class="w">
</span><span class="n">conn</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s2">&quot;CREATE TYPE mini_person AS (name text, age int)&quot;</span><span class="p">)</span><span class="w">
</span><span class="n">info</span> <span class="o">=</span> <span class="n">CompositeInfo</span><span class="o">.</span><span class="n">fetch</span><span class="p">(</span><span class="n">conn</span><span class="p">,</span> <span class="s2">&quot;mini_person&quot;</span><span class="p">)</span><span class="w">
</span><span class="n">register_composite</span><span class="p">(</span><span class="w">
</span> <span class="n">info</span><span class="p">,</span> <span class="n">conn</span><span class="p">,</span> <span class="n">factory</span><span class="o">=</span><span class="n">MiniPerson</span><span class="p">,</span><span class="w">
</span> <span class="n">make_object</span><span class="o">=</span><span class="n">MiniPerson</span><span class="o">.</span><span class="n">from_db</span><span class="p">,</span> <span class="n">make_sequence</span><span class="o">=</span><span class="n">MiniPerson</span><span class="o">.</span><span class="n">to_db</span><span class="p">)</span><span class="w">
</span><span class="n">conn</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s2">&quot;SELECT ('John', 33)::mini_person&quot;</span><span class="p">)</span><span class="o">.</span><span class="n">fetchone</span><span class="p">()[</span><span class="mi">0</span><span class="p">]</span><span class="w">
</span><span class="c1"># MiniPerson(age=33, name='John', height=None)</span><span class="w">
</span><span class="n">conn</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="w">
</span> <span class="s2">&quot;SELECT (</span><span class="si">%(person)s</span><span class="s2">).name || ' next year will be ' || (</span><span class="si">%(person)s</span><span class="s2">).age + 1&quot;</span><span class="p">,</span><span class="w">
</span> <span class="p">{</span><span class="s2">&quot;person&quot;</span><span class="p">:</span> <span class="n">MiniPerson</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s2">&quot;John&quot;</span><span class="p">,</span> <span class="n">age</span><span class="o">=</span><span class="mi">33</span><span class="p">)},</span><span class="w">
</span><span class="p">)</span><span class="o">.</span><span class="n">fetchone</span><span class="p">()[</span><span class="mi">0</span><span class="p">]</span><span class="w">
</span><span class="c1"># 'John next year will be 34'</span>
</pre>
</div>
<div class="section" id="solving-the-fetchone-annoyance-with-type-checkers">
<h2>Solving the <tt class="docutils literal">fetchone()</tt> annoyance with type checkers</h2>
<p>If you use Mypy or other type checkers with Psycopg, you've probably seen
false positives when calling <tt class="docutils literal">fetchone()</tt>. Even if you are 100% certain
your query will return a row, <tt class="docutils literal">fetchone()</tt> is annotated as possibly
returning <tt class="docutils literal">None</tt> - so type checkers complain about patterns like:</p>
<pre class="code python literal-block">
<span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s2">&quot;SELECT count(*) FROM my_table&quot;</span><span class="p">)</span> <span class="c1"># Always returns exactly one value</span><span class="w">
</span><span class="n">count</span> <span class="o">=</span> <span class="n">cur</span><span class="o">.</span><span class="n">fetchone</span><span class="p">()[</span><span class="mi">0</span><span class="p">]</span> <span class="c1"># Error: value of type &quot;tuple | None&quot; is not indexable</span>
</pre>
<p>In Psycopg 3.3, the cursor has become an <a class="reference external" href="https://docs.python.org/3/glossary.html#term-iterator">iterator</a>, whereas it was
previously only an <a class="reference external" href="https://docs.python.org/3/glossary.html#term-iterable">iterable</a>. The distinction is subtle but meaningful: an
iterator holds its own iteration state and does not need to create a new
object for each pass.</p>
<p>More importantly, this change means you can use <a class="reference external" href="https://docs.python.org/3/library/functions.html#next">next()</a> or <a class="reference external" href="https://docs.python.org/3/library/functions.html#anext">anext()</a> to retrieve
a record - and these functions never return <tt class="docutils literal">None</tt>. This makes Mypy happy,
and probably you too:</p>
<pre class="code python literal-block">
<span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s2">&quot;SELECT count(*) FROM my_table&quot;</span><span class="p">)</span><span class="w">
</span><span class="n">count</span> <span class="o">=</span> <span class="nb">next</span><span class="p">(</span><span class="n">cur</span><span class="p">)[</span><span class="mi">0</span><span class="p">]</span>
</pre>
</div>
<div class="section" id="improvements-to-the-connection-pools">
<h2>Improvements to the connection pools</h2>
<p>A connection pool’s parameters can now be changed dynamically - useful for
example to support short-lived secret tokens as passwords, as requested
by some cloud database providers.</p>
<p>A useful <a class="reference external" href="https://www.psycopg.org/psycopg3/docs/api/pool.html#psycopg_pool.ConnectionPool.drain">drain()</a> method is now available to re-create all connections in
a pool. This is helpful, for instance, when the database needs to be
introspected to find the OIDs of extension types to register: without draining
the pool the connections already in the pool would remain stale after the
adapters have been configured.</p>
</div>
<div class="section" id="and-more">
<h2>...And more!</h2>
<p>Other improvements include greater flexibility when navigating results after
a <tt class="docutils literal">fetchmany()</tt> call or after statements returning multiple result sets,
the ability to reconfigure loaders after a query has run, and many other
assorted enhancements. You can find the full list in the <a class="reference external" href="https://www.psycopg.org/psycopg3/docs/news.html#psycopg-3-3-0">psycopg release
notes</a> and the <a class="reference external" href="https://www.psycopg.org/psycopg3/docs/news_pool.html#psycopg-pool-3-3-0">pool release notes</a>!</p>
</div>
<div class="section" id="your-help-is-welcome">
<h2>Your help is welcome</h2>
<p>Psycopg is the de-facto standard for communication between Python and
PostgreSQL - two major components powering countless businesses and
mission-critical infrastructure. Maintaining such an important library to the
highest standards of reliability, performance and security requires a lot of
care and ongoing work.</p>
<p>If you use Python and PostgreSQL and want to help ensure that the interface
between them remains robust and continues to improve, supporting new language
and database features, please consider <a class="reference external" href="https://github.com/sponsors/dvarrazzo">supporting the project</a> 💛</p>
<p>Thank you very much, and happy hacking!</p>
</div>
</content></entry><entry><title>Automatic async to sync code conversion</title><link href="https://www.psycopg.org/articles/2024/09/23/async-to-sync/" rel="alternate"/><updated>2024-09-23T00:00:00Z</updated><author><name>Daniele Varrazzo</name></author><id>urn:uuid:765ce6dc-afc5-34ff-bf78-d5f78cc8aed5</id><content type="html"><p>Psycopg 3 provides both a sync and an async Python interface: for each object
used to perform I/O operations, such as <a class="reference external" href="https://www.psycopg.org/psycopg3/docs/api/connections.html#psycopg.Connection">Connection</a>, <a class="reference external" href="https://www.psycopg.org/psycopg3/docs/api/cursors.html#psycopg.Cursor">Cursor</a>, there is an
async counterpart: <a class="reference external" href="https://www.psycopg.org/psycopg3/docs/api/connections.html#psycopg.AsyncConnection">AsyncConnection</a>, <a class="reference external" href="https://www.psycopg.org/psycopg3/docs/api/cursors.html#psycopg.AsyncCursor">AsyncCursor</a>, with an intuitive
interface: just add the right <tt class="docutils literal">async</tt> or <tt class="docutils literal">await</tt> keyword where needed:</p>
<!-- CUT-HERE -->
<pre class="code python literal-block">
<span class="c1"># Familiar sync code</span><span class="w">
</span><span class="n">conn</span> <span class="o">=</span> <span class="n">psycopg</span><span class="o">.</span><span class="n">Connection</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="s2">&quot;&quot;</span><span class="p">)</span><span class="w">
</span><span class="n">cur</span> <span class="o">=</span> <span class="n">conn</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s2">&quot;select now()&quot;</span><span class="p">)</span><span class="w">
</span><span class="nb">print</span><span class="p">(</span><span class="n">cur</span><span class="o">.</span><span class="n">fetchone</span><span class="p">()[</span><span class="mi">0</span><span class="p">])</span><span class="w">
</span><span class="c1"># Similar async code</span><span class="w">
</span><span class="n">aconn</span> <span class="o">=</span> <span class="k">await</span> <span class="n">psycopg</span><span class="o">.</span><span class="n">AsyncConnection</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="s2">&quot;&quot;</span><span class="p">)</span><span class="w">
</span><span class="n">acur</span> <span class="o">=</span> <span class="k">await</span> <span class="n">aconn</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s2">&quot;select now()&quot;</span><span class="p">)</span><span class="w">
</span><span class="nb">print</span><span class="p">((</span><span class="k">await</span> <span class="n">acur</span><span class="o">.</span><span class="n">fetchone</span><span class="p">())[</span><span class="mi">0</span><span class="p">])</span>
</pre>
<p>The decision to provide both sync and async code <a class="reference external" href="https://www.varrazzo.com/blog/2020/03/26/psycopg3-first-report/">was made early in the
development of Psycopg 3</a> and most of the internal code is written in a way
to be compatible with both sync and async code, in order to keep code
duplication to a minimum. This was achieved by making all the libpq
communication async, and writing the network code as generators,
<tt class="docutils literal">yield</tt>ing at the moment they need to wait, isolating the differences in
the sync/async wait policy all in <tt class="docutils literal">wait()</tt> functions.</p>
<p>This helped to minimise the async/sync differences in the code related to the
communication between PostgreSQL and Psycopg. However, the interface between
Psycopg and the Python user is still a lot to maintain, and consists of a lot
of code that is very similar, almost duplicated, between the sync and async
sided. Apart from the obvious <tt class="docutils literal">async</tt>/<tt class="docutils literal">await</tt> keywords, there would be
subtle implementation differences, for example:</p>
<ul class="simple">
<li>using <tt class="docutils literal">asyncio</tt> functions instead of blocking counterparts, for instance
<tt class="docutils literal">await asyncio.sleep()</tt> instead of <tt class="docutils literal">time.sleep()</tt>;</li>
<li><tt class="docutils literal">asyncio.create_task(f(arg1, arg2))</tt> is similar to <tt class="docutils literal">thread.Thread(f,
(arg1, <span class="pre">arg2)).start()</span></tt>;</li>
<li><tt class="docutils literal">threading.Event</tt> has a <tt class="docutils literal">asyncio.Event</tt> counterpart whose <tt class="docutils literal">lock()</tt>
method doesn't have a <tt class="docutils literal">timeout</tt>, parameter, so <tt class="docutils literal">event.wait(timeout=10)</tt>
needs to be rewritten as <tt class="docutils literal"><span class="pre">asyncio.wait_for(event.wait(),</span> timeout=10)</tt>.</li>
</ul>
<p>Up until Psycopg 3.1, the two variants of each object were kept in sync
manually. Every time changes were made on the sync side, they had to be ported
to the async side, with cumbersome and noisy diffs, with subtle differences
being introduced from time to time. Even the tests were pretty much duplicated
(with some sync tests being accidentally lost on the async side, or vice
versa). It seemed like a situation that could have been improved.</p>
<div class="section" id="this-is-so-boring-that">
<h2>This is so boring that...</h2>
<p>...a computer should do it for me instead.</p>
<p>Writing the async side starting from the sync side? Actually, the opposite. It
is obvious that the async side has more information than the sync side (every
method definition and call clearly indicates whether it will block or not) and
most of the differences are minimal and repetitive. What we want then is <em>a
script that takes asyncio-based source code as input and outputs
equivalent sync code</em>.</p>
<p>This article describes what we did to implement such a script and how we used
it for the initial transformation (replacing manually written sync code with
auto-generated code without loss of quality) and how we are currently using it
to maintain the Psycopg 3 codebase.</p>
</div>
<div class="section" id="abstract-syntax-tree">
<h2>Abstract Syntax Tree</h2>
<p>You would be tempted to write a bunch of regular expressions to just scrub
away every <tt class="docutils literal">async</tt> and <tt class="docutils literal">await</tt> keyword found, but the source code is
probably the wrong level to attack the problem: Python knows how to parse
Python itself well and can allow us to reason at a higher level.</p>
<p>A better tool to work with is the <a class="reference external" href="https://en.wikipedia.org/wiki/Abstract_syntax_tree">Abstract Syntax Tree</a> (AST): an in-memory
representation of the code obtained after parsing. At this level we manipulate
objects that represent &quot;the for loop&quot;, or &quot;the function call&quot;, and we are not
fooled by unexpected spaces, extra brackets, comments, literal strings, and
other traps.</p>
<p>The <a class="reference external" href="https://docs.python.org/3/library/ast.html">Python 'ast' module</a> is the obvious starting point: if you have a bit
of source code such as:</p>
<pre class="code python literal-block">
<span class="kn">import</span><span class="w"> </span><span class="nn">asyncio</span><span class="w">
</span><span class="k">async</span> <span class="k">def</span><span class="w"> </span><span class="nf">async_square</span><span class="p">(</span><span class="n">n</span><span class="p">):</span><span class="w">
</span> <span class="c1"># Squares are slow</span><span class="w">
</span> <span class="k">await</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">sleep</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span><span class="w">
</span> <span class="k">return</span> <span class="n">n</span> <span class="o">*</span> <span class="n">n</span>
</pre>
<p>you can pass it to the module to see the AST tree that represents it:</p>
<pre class="literal-block">
$ python -m ast ast1.py
<strong>Module</strong>(
body=[
<strong>Import</strong>(
names=[
alias(name='asyncio')]),
<strong>AsyncFunctionDef</strong>(
name='async_square',
args=arguments(
args=[
arg(arg='n')],
defaults=[]),
body=[
Expr(
value=<strong>Await</strong>(
value=<strong>Call</strong>(
func=Attribute(
value=Name(id='asyncio'),
attr='sleep'),
args=[
Constant(value=1)]))),
<strong>Return</strong>(
value=BinOp(
left=Name(id='n'),
op=Mult(),
right=Name(id='n')))],
decorator_list=[],
returns=Name(id='float'))])
</pre>
<p>You can see, highlighted, the nodes in the tree representing the main
statements in the code: the tree represents a <em>module</em>, whose body contains two
<em>statements</em> - an <tt class="docutils literal">import</tt> and an <tt class="docutils literal">async def</tt> - with the function body
defining an <tt class="docutils literal">await</tt> call and a <tt class="docutils literal">return</tt> statement.</p>
<p>The same <tt class="docutils literal">ast</tt> module can perform the reverse transformation, converting an
AST tree back to source:</p>
<pre class="literal-block">
$ python -c &quot;import ast; print(ast.unparse(ast.parse(open('ast1.py').read())))&quot;
import asyncio
async def square(n: float) -&gt; float:
await asyncio.sleep(1)
return n * n
</pre>
<p>As you can see, the transformation back to code is unfortunately not a perfect
reconstruction of the original code, it is only <em>equivalent</em>, with missing
comments and different spacing. This is because the syntax tree is <em>abstract</em>
and whitespaces and comments don't affect it. If you wanted to take those
details into account you would need a <em>concrete</em> syntax tree (<a class="reference external" href="https://pypi.org/project/libcst/">something like
that exists</a>, but I haven't played with it).</p>
<p>Changing whitespaces is not a problem, but losing comments can be, especially
when they are used to control linters (such as Flake8's <tt class="docutils literal">noqa</tt> or Mypy's
<tt class="docutils literal">type: ignore</tt>), or simply when you happen to be a human being and want to
read the source code. Fortunately there is a simple wrapper module,
<a class="reference external" href="https://pypi.org/project/ast-comments/">ast-comments</a>, which does exactly what it says on the tin: it introduces
<tt class="docutils literal">Comment</tt> nodes as part of an AST. Playing around with it, it turned out to
be a good compromise between an abstract and a concrete syntax tree, after
some taming of the comments placement.</p>
</div>
<div class="section" id="du-ast-mich">
<h2>Du AST Mich</h2>
<p>To perform the code transformation, we will walk over the abstract
syntax tree and we will perform some operation to generate a different tree of
our liking. Typically, this type of operation is performed using an
implementation of the <a class="reference external" href="https://en.wikipedia.org/wiki/Visitor_pattern">visitor pattern</a>.</p>
<p>This pattern can be incredibly useful whenever you need to perform operations
on data structures composed of heterogeneous nodes (I've seen it in
applications ranging from converting UML representations to code, converting
markup language to HTML, converting Kubernetes manifests to Helm charts,
converting annotated lyrics files to Ukulele tab sheets...); unfortunately
many of the descriptions of the pattern you can find online fail to make its
brilliance immediately apparent (the Wikipedia page is pretty bad at it)
because they have historically focused on solving the <em>double-dispatch</em>
problem in static languages like as C++ or Java (which is trivial in a dynamic
language like Python) rather than focusing on the <strong>awesome</strong> things you
can do with it.</p>
<p>In a nutshell, you will have an object that traverses an input data structure,
element by element, building an output structure in the process, allowing you
to run different code and to perform different manipulations depending on the
type of element being traversed.</p>
<p>In our case, both the input and the output are AST trees, which will happen to
be very similar to each other (since we are just trying to translate some
subtle differences from one Python module to another): for many nodes, the
visitor will just output a copy of it (for example, the <tt class="docutils literal">return</tt> statement
in the above example is unchanged). But, if we see a pattern of interest, we
can tell our visitor to produce a different node.</p>
<p>The <tt class="docutils literal">ast</tt> module provides a base class <a class="reference external" href="https://docs.python.org/3/library/ast.html#ast.NodeTransformer">ast.NodeTransformer</a> which
implements the node traversal and tree production parts. By itself it
doesn't perform any operations on the nodes, so it just produces a copy of the
input tree. However, by subclassing the class and adding visit methods, you
can implement node-specific transformations.</p>
<p>With the AST node transformer, the method called is based on the name of the
node being visited; for example, if you add a method called <tt class="docutils literal">visit_Import</tt>
to your subclass, the visitor will call it whenever it traverses an <tt class="docutils literal">Import</tt>
node, giving you the chance to manipulate an <tt class="docutils literal">import</tt> statement. You can
then decide whether you want to change some of the details of the node (drop
some imports, change some names), or replace the node with something completely
different (such as replacing an async function definition with a sync one).</p>
<p>Let's say that we want to produce a sync version of the above script: the
differences should be the following:</p>
<pre class="code diff literal-block">
<span class="gu">&#64;&#64; -1,7 +1,7 &#64;&#64;</span><span class="w">
</span><span class="gd">-import asyncio</span><span class="w">
</span><span class="gi">+import time</span><span class="w">
</span><span class="gd">-async def async_square(n: float) -&gt; float:</span><span class="w">
</span><span class="gi">+def square(n: float) -&gt; float:</span><span class="w">
</span> # Squares are slow<span class="w">
</span><span class="gd">- await asyncio.sleep(1)</span><span class="w">
</span><span class="gi">+ time.sleep(1)</span><span class="w">
</span> return n * n
</pre>
<p>In our toy example, we want to convert the <tt class="docutils literal">asyncio</tt> module into the <tt class="docutils literal">time</tt>
module (which is obviously not the right thing to do in the general case, but
let's keep the example simple). The following script implements the
transformation and prints the converted module:</p>
<pre class="code python literal-block">
<span class="kn">import</span><span class="w"> </span><span class="nn">ast</span><span class="w">
</span><span class="k">class</span><span class="w"> </span><span class="nc">MyTransformer</span><span class="p">(</span><span class="n">ast</span><span class="o">.</span><span class="n">NodeTransformer</span><span class="p">):</span><span class="w">
</span> <span class="k">def</span><span class="w"> </span><span class="nf">visit_Import</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">node</span><span class="p">):</span><span class="w">
</span> <span class="k">for</span> <span class="n">alias</span> <span class="ow">in</span> <span class="n">node</span><span class="o">.</span><span class="n">names</span><span class="p">:</span><span class="w">
</span> <span class="k">if</span> <span class="n">alias</span><span class="o">.</span><span class="n">name</span> <span class="o">==</span> <span class="s2">&quot;asyncio&quot;</span><span class="p">:</span><span class="w">
</span> <span class="n">alias</span><span class="o">.</span><span class="n">name</span> <span class="o">=</span> <span class="s2">&quot;time&quot;</span><span class="w">
</span> <span class="k">return</span> <span class="n">node</span><span class="w">
</span><span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s2">&quot;ast1.py&quot;</span><span class="p">)</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span><span class="w">
</span> <span class="n">tree</span> <span class="o">=</span> <span class="n">ast</span><span class="o">.</span><span class="n">parse</span><span class="p">(</span><span class="n">f</span><span class="o">.</span><span class="n">read</span><span class="p">())</span><span class="w">
</span><span class="n">tree</span> <span class="o">=</span> <span class="n">MyTransformer</span><span class="p">()</span><span class="o">.</span><span class="n">visit</span><span class="p">(</span><span class="n">tree</span><span class="p">)</span><span class="w">
</span><span class="nb">print</span><span class="p">(</span><span class="n">ast</span><span class="o">.</span><span class="n">unparse</span><span class="p">(</span><span class="n">tree</span><span class="p">))</span>
</pre>
<p>The script will print the new source, with an <tt class="docutils literal">import time</tt> replacing the
original <tt class="docutils literal">import asyncio</tt>.</p>
<p>Changing the <tt class="docutils literal">async</tt> call is a bit trickier: we want to change the
highlighted parts of the original tree:</p>
<pre class="literal-block">
<strong>value=Await</strong>( &lt;&lt; this node must be dropped, replaced by its <strong>value</strong>
value=Call(
func=Attribute(
value=Name(id='<strong>asyncio</strong>'), &lt;&lt; we want <strong>time</strong> here
attr='sleep'),
args=[
Constant(value=1)],
keywords=[]))),
</pre>
<p>Adding the following two methods to the above class will implement what has
been described.</p>
<pre class="code python literal-block">
<span class="k">def</span><span class="w"> </span><span class="nf">visit_Await</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">node</span><span class="p">):</span><span class="w">
</span> <span class="n">new_node</span> <span class="o">=</span> <span class="n">node</span><span class="o">.</span><span class="n">value</span> <span class="c1"># drop the node, continue to operate on the value</span><span class="w">
</span> <span class="bp">self</span><span class="o">.</span><span class="n">visit</span><span class="p">(</span><span class="n">new_node</span><span class="p">)</span><span class="w">
</span> <span class="k">return</span> <span class="n">new_node</span><span class="w">
</span><span class="k">def</span><span class="w"> </span><span class="nf">visit_Call</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">node</span><span class="p">):</span><span class="w">
</span> <span class="k">match</span> <span class="n">node</span><span class="o">.</span><span class="n">func</span><span class="p">:</span><span class="w">
</span> <span class="k">case</span> <span class="n">ast</span><span class="o">.</span><span class="n">Attribute</span><span class="p">(</span><span class="n">value</span><span class="o">=</span><span class="n">ast</span><span class="o">.</span><span class="n">Name</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="s2">&quot;asyncio&quot;</span><span class="p">),</span> <span class="n">attr</span><span class="o">=</span><span class="s2">&quot;sleep&quot;</span><span class="p">):</span><span class="w">
</span> <span class="n">node</span><span class="o">.</span><span class="n">func</span><span class="o">.</span><span class="n">value</span><span class="o">.</span><span class="n">id</span> <span class="o">=</span> <span class="s2">&quot;time&quot;</span><span class="w">
</span> <span class="k">return</span> <span class="n">node</span>
</pre>
<p>To make sense of how these methods operate on their input nodes, and then to
implement your own transformations, you can always look at the output of
<tt class="docutils literal">python <span class="pre">-m</span> ast</tt> in order to see the attributes on each node and how they are
nested.</p>
<p>The <tt class="docutils literal">visit_Call</tt> method shows how the <a class="reference external" href="https://peps.python.org/pep-0636/">structural pattern matching</a>
introduced in Python 3.10 comes in handy for this operation. The method is
called for each function call found in the input code; checking whether the
one just received requires any manipulation would have involved a cascade of
ifs (the value is a <tt class="docutils literal">Name</tt>, its id is <tt class="docutils literal">asyncio</tt>, the attr is <tt class="docutils literal">sleep</tt>...)
which becomes pretty ugly pretty quickly, whereas instead a <tt class="docutils literal">match</tt>
statement can describe a complex nested test very succinctly.</p>
</div>
<div class="section" id="problems-with-sleep">
<h2>Problems with <tt class="docutils literal">sleep()</tt></h2>
<p>Performing the transformation from <tt class="docutils literal">asyncio.sleep</tt> to <tt class="docutils literal">time.sleep</tt> for
real is much more complex than this. What if our source includes <tt class="docutils literal">from asycio
import sleep, Event</tt>? We would have to split the import into several parts:</p>
<pre class="code python literal-block">
<span class="kn">from</span><span class="w"> </span><span class="nn">time</span><span class="w"> </span><span class="kn">import</span> <span class="n">sleep</span><span class="w">
</span><span class="kn">from</span><span class="w"> </span><span class="nn">threading</span><span class="w"> </span><span class="kn">import</span> <span class="n">Event</span>
</pre>
<p>and the latter should be treated differently later because the two <tt class="docutils literal">Event</tt>
objects have a different <tt class="docutils literal">wait()</tt> signatures.</p>
<p>To help with this operation, in Psycopg 3 we introduced <a class="reference external" href="https://github.com/psycopg/psycopg/blob/d13137aacb82fed79459a9dd487846a2ec972571/psycopg/psycopg/_acompat.py">an internal
'_acompat' module</a> (actually <a class="reference external" href="https://github.com/psycopg/psycopg/blob/d13137aacb82fed79459a9dd487846a2ec972571/psycopg_pool/psycopg_pool/_acompat.py">two</a>, because the pool is released
separately and uses different functions; actually <a class="reference external" href="https://github.com/psycopg/psycopg/blob/d13137aacb82fed79459a9dd487846a2ec972571/tests/acompat.py">three</a>, because the tests
also have their own...) to expose pairs of functions or objects that should be
used alternatively in sync or in async mode.</p>
<p>For example we can solve the <tt class="docutils literal">sleep()</tt> problem with:</p>
<pre class="code python literal-block">
<span class="c1"># module _acompat.py</span><span class="w">
</span><span class="kn">import</span><span class="w"> </span><span class="nn">time</span><span class="w">
</span><span class="kn">import</span><span class="w"> </span><span class="nn">asyncio</span><span class="w">
</span><span class="n">sleep</span> <span class="o">=</span> <span class="n">time</span><span class="o">.</span><span class="n">sleep</span><span class="w">
</span><span class="k">def</span><span class="w"> </span><span class="nf">asleep</span><span class="p">(</span><span class="n">seconds</span><span class="p">:</span> <span class="nb">float</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="n">Coroutine</span><span class="p">[</span><span class="n">Any</span><span class="p">,</span> <span class="n">Any</span><span class="p">,</span> <span class="kc">None</span><span class="p">]:</span><span class="w">
</span><span class="sd">&quot;&quot;&quot;
Equivalent to asyncio.sleep(), converted to time.sleep() by async_to_sync.
&quot;&quot;&quot;</span><span class="w">
</span> <span class="k">return</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">sleep</span><span class="p">(</span><span class="n">seconds</span><span class="p">)</span>
</pre>
<p>Now it's easy to use <tt class="docutils literal">from ._acompat import asleep; await asleep(1)</tt> and do
some simple name substitutions in the AST: the resulting statement <tt class="docutils literal">from
._acompat import sleep; sleep(1)</tt> will work as expected.</p>
<p>Other goodies we have implemented to help unify async and sync code are
<tt class="docutils literal">aspawn</tt>/<tt class="docutils literal">spawn</tt> and <tt class="docutils literal">agather</tt>/<tt class="docutils literal">gather</tt> to unify threads and
asyncio tasks creation, <tt class="docutils literal">alist()</tt> to encapsulate <tt class="docutils literal">[x for x in await
iterable]</tt> in a way that can be easily converted to <tt class="docutils literal">list(iterable)</tt> and
many other helpers to smooth the transition.</p>
</div>
<div class="section" id="when-everything-else-fail">
<h2>When everything else fail</h2>
<p>There may be parts of the codebase where the difference between sync and async
versions is too difficult to handle in a practical way, and is not worth to
put together a complex matching for a complex, one-off case. What we want is a
simple &quot;if async, do this, else do that&quot;.</p>
<p>We have solved this problem by using a pattern like:</p>
<pre class="code python literal-block">
<span class="k">if</span> <span class="kc">True</span><span class="p">:</span> <span class="c1"># ASYNC</span><span class="w">
</span> <span class="n">foo</span><span class="p">()</span><span class="w">
</span><span class="k">else</span><span class="p">:</span><span class="w">
</span> <span class="n">bar</span><span class="p">()</span>
</pre>
<p>The AST with this code, including the comments, looks like:</p>
<pre class="literal-block">
Module(
body=[
<strong>If(</strong>
<strong>test=Constant(value=True),</strong>
body=[
<strong>Comment(value='# ASYNC', inline=True),</strong>
Expr(
value=Call(
func=Name(id='foo'),
args=[],
keywords=[]))],
orelse=[
Expr(
value=Call(
func=Name(id='bar'),
args=[],
keywords=[]))])],
type_ignores=[])
</pre>
<p><a class="reference external" href="https://github.com/psycopg/psycopg/blob/d13137aacb82fed79459a9dd487846a2ec972571/tools/async_to_sync.py#L253-L262">Our transformation</a> will find the <tt class="docutils literal">ASYNC</tt> comment: in this case it will
simply discard the if side of the condition, as well as the <tt class="docutils literal">if</tt> itself, and
will leave only the <tt class="docutils literal">else</tt> branch in the sync code, allowing you to discard
unneeded imports or other code that would simply be invalid in the sync
context.</p>
<p>This pattern is also efficient, because the Python compiler is able to
recognise that <tt class="docutils literal">if True</tt> will always take the first branch, so it will
discard the test and the code in the <tt class="docutils literal">else</tt> branch. The <a class="reference external" href="https://docs.python.org/3/library/dis.html">dis</a>(assembler)
module shows no jump and that no reference to the <tt class="docutils literal">bar()</tt> function call:</p>
<pre class="literal-block">
$ python -m dis ast3.py
1 0 NOP
2 2 LOAD_NAME 0 (foo)
4 CALL_FUNCTION 0
6 POP_TOP
8 LOAD_CONST 1 (None)
10 RETURN_VALUE
</pre>
</div>
<div class="section" id="conversion-methodology">
<h2>Conversion methodology</h2>
<p>Once we have our conversion script, how do we use it to actually convert the
code base, making sure to not break it? The process, for us, was
iterative: going module by module and adding features to the script until
all the &quot;duplicated&quot; modules were complete.</p>
<p>For each module to be converted, the procedure was roughly as follows.</p>
<p>First step: refactoring the code with the intention of not changing any
behaviour, but of making the async module as similar as possible to the sync
module. This might have meant some code reorganisation, the renaming of some
variables, the swapping of some function definitions, the rediscovery of some
forgotten skeletons and a chance of giving them a proper burial.</p>
<p>Often we would have implemented some non-I/O related helper function on the
sync side and imported it on the async side:</p>
<pre class="code python literal-block">
<span class="c1"># connection.py</span><span class="w">
</span><span class="k">def</span><span class="w"> </span><span class="nf">clean_up_conninfo</span><span class="p">(</span><span class="n">conninfo</span><span class="p">):</span><span class="w">
</span> <span class="o">...</span> <span class="c1"># hack hack</span><span class="w">
</span> <span class="k">return</span> <span class="n">better_conninfo</span><span class="w">
</span><span class="k">def</span><span class="w"> </span><span class="nf">connect</span><span class="p">(</span><span class="n">conninfo</span><span class="p">):</span><span class="w">
</span> <span class="n">better_conninfo</span> <span class="o">=</span> <span class="n">clean_up_conninfo</span><span class="p">(</span><span class="n">conninfo</span><span class="p">)</span><span class="w">
</span> <span class="n">conn</span> <span class="o">=</span> <span class="n">wait</span><span class="p">(</span><span class="n">connection_gen</span><span class="p">(</span><span class="n">bettern_conninfo</span><span class="p">))</span><span class="w">
</span> <span class="k">return</span> <span class="n">conn</span><span class="w">
</span><span class="c1"># connection_async.py</span><span class="w">
</span><span class="kn">from</span><span class="w"> </span><span class="nn">.connection</span><span class="w"> </span><span class="kn">import</span> <span class="n">clean_up_conninfo</span><span class="w">
</span><span class="k">async</span> <span class="k">def</span><span class="w"> </span><span class="nf">connect_async</span><span class="p">(</span><span class="n">conninfo</span><span class="p">):</span><span class="w">
</span> <span class="n">better_conninfo</span> <span class="o">=</span> <span class="n">clean_up_conninfo</span><span class="p">(</span><span class="n">conninfo</span><span class="p">)</span><span class="w">
</span> <span class="n">aconn</span> <span class="o">=</span> <span class="k">await</span> <span class="n">async_wait</span><span class="p">(</span><span class="n">connection_gen</span><span class="p">(</span><span class="n">bettern_conninfo</span><span class="p">))</span><span class="w">
</span> <span class="k">return</span> <span class="n">aconn</span>
</pre>
<p>In this case we would have moved the shared functionality in a separate
internal module and imported the function on both the sides:</p>
<pre class="code python literal-block">
<span class="c1"># _connection.py</span><span class="w">
</span><span class="k">def</span><span class="w"> </span><span class="nf">clean_up_conninfo</span><span class="p">(</span><span class="n">conninfo</span><span class="p">):</span><span class="w">
</span> <span class="o">...</span> <span class="c1"># hack hack</span><span class="w">
</span> <span class="k">return</span> <span class="n">better_conninfo</span><span class="w">
</span><span class="c1"># connection.py</span><span class="w">
</span><span class="kn">from</span><span class="w"> </span><span class="nn">._connection</span><span class="w"> </span><span class="kn">import</span> <span class="n">clean_up_conninfo</span><span class="w">
</span><span class="k">def</span><span class="w"> </span><span class="nf">connect</span><span class="p">(</span><span class="n">conninfo</span><span class="p">):</span><span class="w">
</span> <span class="n">better_conninfo</span> <span class="o">=</span> <span class="n">clean_up_conninfo</span><span class="p">(</span><span class="n">conninfo</span><span class="p">)</span><span class="w">
</span> <span class="n">conn</span> <span class="o">=</span> <span class="n">wait</span><span class="p">(</span><span class="n">connection_gen</span><span class="p">(</span><span class="n">bettern_conninfo</span><span class="p">))</span><span class="w">
</span> <span class="k">return</span> <span class="n">conn</span><span class="w">
</span><span class="c1"># connection_async.py</span><span class="w">
</span><span class="kn">from</span><span class="w"> </span><span class="nn">._connection</span><span class="w"> </span><span class="kn">import</span> <span class="n">clean_up_conninfo</span><span class="w">
</span><span class="k">async</span> <span class="k">def</span><span class="w"> </span><span class="nf">connect_async</span><span class="p">(</span><span class="n">conninfo</span><span class="p">):</span><span class="w">
</span> <span class="n">better_conninfo</span> <span class="o">=</span> <span class="n">clean_up_conninfo</span><span class="p">(</span><span class="n">conninfo</span><span class="p">)</span><span class="w">
</span> <span class="n">aconn</span> <span class="o">=</span> <span class="k">await</span> <span class="n">async_wait</span><span class="p">(</span><span class="n">connection_gen</span><span class="p">(</span><span class="n">bettern_conninfo</span><span class="p">))</span><span class="w">
</span> <span class="k">return</span> <span class="n">aconn</span>
</pre>
<p>Now that the two modules are more similar we can run the test suite to verify
that the library still works and can commit the current state to git.</p>
<p>Second step: run an async -&gt; sync conversion with the current version of the
script. Even running a no-op script is useful: it produces changes that can be
easily seen with <tt class="docutils literal">git diff</tt>, suggesting which conversion feature is missing,
or what further cleanup we could have done in the code to make the sync and
async flavours more similar.</p>
<p>For example, a no-op script that just copies the async side to the sync
side, would show up in <tt class="docutils literal">git diff</tt> as:</p>
<pre class="code diff literal-block">
<span class="gu">&#64;&#64; -1,6 +1,6 &#64;&#64;</span><span class="w">
</span>from ._connection import clean_up_conninfo<span class="w">
</span><span class="gd">-def connect(conninfo):</span><span class="w">
</span><span class="gi">+async def connect_async(conninfo):</span><span class="w">
</span> better_conninfo = clean_up_conninfo(conninfo)<span class="w">
</span><span class="gd">- conn = wait(connection_gen(bettern_conninfo))</span><span class="w">
</span><span class="gd">- return conn</span><span class="w">
</span><span class="gi">+ aconn = await async_wait(connection_gen(bettern_conninfo))</span><span class="w">
</span><span class="gi">+ return aconn</span>
</pre>
<p>The first feature to add to the conversion script is to remove the <tt class="docutils literal">async</tt>
and <tt class="docutils literal">await</tt> keywords. Run the conversion and diff again and you will see:</p>
<pre class="code diff literal-block">
<span class="gu">&#64;&#64; -1,6 +1,6 &#64;&#64;</span><span class="w">
</span>from ._connection import clean_up_conninfo<span class="w">
</span><span class="gd">-def connect(conninfo):</span><span class="w">
</span><span class="gi">+def connect_async(conninfo):</span><span class="w">
</span> better_conninfo = clean_up_conninfo(conninfo)<span class="w">
</span><span class="gd">- conn = wait(connection_gen(bettern_conninfo))</span><span class="w">
</span><span class="gd">- return conn</span><span class="w">
</span><span class="gi">+ aconn = async_wait(connection_gen(bettern_conninfo))</span><span class="w">
</span><span class="gi">+ return aconn</span>
</pre>
<p>The next step is some renaming. If <tt class="docutils literal">connect()</tt> and <tt class="docutils literal">connect_async()</tt>
are public functions we don't want to change their names. The script should
have a name mapping function suggesting to convert:</p>
<ul class="simple">
<li><tt class="docutils literal">connect_async</tt> -&gt; <tt class="docutils literal">connect</tt></li>
<li><tt class="docutils literal">wait_async</tt> -&gt; <tt class="docutils literal">wait</tt></li>
</ul>
<p>Implementing this renaming in the AST we would bring us to the diff:</p>
<pre class="code diff literal-block">
<span class="gu">&#64;&#64; -2,5 +2,5 &#64;&#64;</span><span class="w">
</span>def connect(conninfo):<span class="w">
</span> better_conninfo = clean_up_conninfo(conninfo)<span class="w">
</span><span class="gd">- conn = wait(libpq.connect_async())</span><span class="w">
</span><span class="gd">- return conn</span><span class="w">
</span><span class="gi">+ aconn = async(libpq.connect_async())</span><span class="w">
</span><span class="gi">+ return aconn</span>
</pre>
<p>We are getting there. This remaining <tt class="docutils literal">aconnn</tt>/<tt class="docutils literal">conn</tt> is actually a
gratuitous difference: we can change the async side and call the local
variable <tt class="docutils literal">conn</tt> without losing readability and obviously without changing
any behaviour.</p>
<p>Committing the change on the async side and re-running the conversion would
show no more difference on the sync side. At this point we can commit the
whole project (any remaining but acceptable change on the sync side, the new
features added to the conversion script, new entries in the renaming
mapping...), run the tests to verify that no regression has been introduced,
and move on to the next module.</p>
<p>This operation, in Psycopg 3, started at commit <a class="reference external" href="https://github.com/psycopg/psycopg/commit/765f663f171bf5d5e4862d5c4a5d572b7e3227d8">765f663f</a> and can be seen in
the git history as a parallel branch that was eventually merged in <a class="reference external" href="https://github.com/psycopg/psycopg/commit/8bb0f9bfef945861e8f671fba9073b3fae45c67f">8bb0f9bf</a>.
The <tt class="docutils literal">diff <span class="pre">--stat</span></tt> shows a whopping:</p>
<pre class="literal-block">
99 files changed, 9697 insertions(+), 8486 deletions(-)
</pre>
<p>which is obviously a monster changeset, but mostly consists of incremental
refactorings, conversions, finding new ways to minimise differences. It could
be an interesting ride if you have a project where you need to introduce
a similar automatic conversion.</p>
</div>
<div class="section" id="the-final-result">
<h2>The final result</h2>
<p>Here is the <a class="reference external" href="https://github.com/psycopg/psycopg/blob/3.2.0/tools/async_to_sync.py">Psycopg 3 async to sync conversion script</a> (as of the <a class="reference external" href="https://www.psycopg.org/articles/2024/06/30/psycopg-32-released/">Psycopg
3.2 release</a>). At the time of writing, It processes 27 files and
automatically generates about the 25% of the codebase. Some of the features it
boasts:</p>
<ul>
<li><p class="first">the AST transformations described above, including tricks like recursion
into strings containing code to be transformed, such as Mypy annotations
expressed as strings, adjusting the output and the comments to make the
resulting unparsed code almost as good as the handwritten side;</p>
</li>
<li><p class="first">it inserts non-essential whitespace, and runs <a class="reference external" href="https://black.readthedocs.io/">black</a> on the output, in
order to make the resulting code as uniform as possible to the original and
as good for humans to work with (to read, debug, diff, etc);</p>
</li>
<li><p class="first">since different Python versions may generate different ASTs and different
output code, it can run in a Docker container, whose image is created on the
fly using as base the Python image of the reference version;</p>
</li>
<li><p class="first">it adds a useful disclaimer to the top of the file:</p>
<pre class="code python literal-block">
<span class="c1"># WARNING: this file is auto-generated by 'async_to_sync.py'</span><span class="w">
</span><span class="c1"># from the original file 'connection_async.py'</span><span class="w">
</span><span class="c1"># DO NOT CHANGE! Change the original file instead.</span>
</pre>
</li>
<li><p class="first">it has a &quot;check&quot; mode that runs in Github Action upon every commit, as part
of the lint step, and will fail if it finds any files to convert that haven't
been committed;</p>
</li>
<li><p class="first">the check mode has its own check: if any script containing the above disclaimer
is not included in the list of files to be converted, it will throw an
error (because a converted file has not been added to the automatic
conversion list);</p>
</li>
<li><p class="first">the check of the check also has its own check! If no file with the
disclaimer is found then it means that something is wrong... Maybe the
disclaimer has been rewritten and the check doesn't work anymore;</p>
</li>
<li><p class="first">it can run in parallel and only on the files that have changed. Almost as
good as <tt class="docutils literal">make</tt> (but for certain tasks it is useful to have all the input
files at once, therefore, &quot;better than <tt class="docutils literal">make</tt>&quot;).</p>
</li>
</ul>
<p>The code is specific to the Psycopg 3 codebase and formatting style, so it's
probably not ready to be used as it is in other projects. But it is probably a
good starting point to to your own conversion: change the list of files to
process, the name mapping, and you should be good to start.</p>
<p>Hope this helps. Happy hacking!</p>
</div>
</content></entry><entry><title>Psycopg 3.2 released</title><link href="https://www.psycopg.org/articles/2024/06/30/psycopg-32-released/" rel="alternate"/><updated>2024-06-30T00:00:00Z</updated><author><name>Daniele Varrazzo</name></author><id>urn:uuid:31cb8a57-f930-3fb0-82c6-4067eb76bd76</id><content type="html"><p>It was quite the ride! But we made it!</p>
<p>After almost two years, 846 commits, more than 700 new tests, more than 20000
changes in 310 files (I didn't even realise that there were 310 files in this
project...) Psycopg 3.2 has been released!</p>
<p>This release brings a few new feature and hopefully no meaningful non-backward
compatible change. The whole list of changes is available <a class="reference external" href="https://www.psycopg.org/psycopg3/docs/news.html#psycopg-3-2">in the changelog</a>; these are
some of the major points explained.</p>
<!-- CUT-HERE -->
<div class="section" id="numpy-scalars-support">
<h2>Numpy scalars support</h2>
<p>In many scientific applications, <a class="reference external" href="https://numpy.org/doc/stable/reference/arrays.scalars.html#built-in-scalar-types">Numpy scalars</a>
are widely used, either by themselves or in conjunction with regular Python
values. However there was no support for storing them to the database and a
conversion to normal Python values was necessary. Starting from Psycopg 3.2
storing Numpy scalars is automatic and the operation efficient.</p>
<p>A natural extension would be to convert between Numpy and PostgreSQL arrays
too. However there hasn't been much demand for the feature, therefore it's
currently <a class="reference external" href="https://github.com/psycopg/psycopg/issues/336">on the back burner</a> but can be implemented if
there is demand.</p>
</div>
<div class="section" id="postgresql-parameters">
<h2>PostgreSQL parameters</h2>
<p>Psycopg uses placeholders such as <tt class="docutils literal">%s</tt> and <tt class="docutils literal">%(name)s</tt> to <a class="reference external" href="https://www.psycopg.org/psycopg3/docs/basic/params.html">pass values to
queries</a>. These
formats are familiar to Python developers, but they are quite foreign in