File size: 99,389 Bytes
0e239c6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
diff --git a/docs/howto/fmt.md b/docs/howto/fmt.md
new file mode 100644
index 000000000..1d874b40b
--- /dev/null
+++ b/docs/howto/fmt.md
@@ -0,0 +1,68 @@
+# `fmt` - Formatting queries
+
+`sqlc fmt` rewrites the query files referenced by your configuration file in a
+canonical format. Each query is parsed with the engine's parser and printed
+back from the syntax tree, so formatting never depends on how the query was
+written — only on what it means.
+
+Like `gofmt`, the formatter does not impose a maximum line width. A statement
+written on a single line stays on a single line, and a statement the author
+broke across lines keeps its breaks: the printer notices which clause
+boundaries (`FROM`, `WHERE`, `ORDER BY`, ...) and list boundaries the author
+broke at and preserves them, normalizing indentation and spacing around them.
+
+Comments inside a statement are formatted along with it: each comment is
+anchored to the code around it by source position and printed back there —
+a comment trailing a select-list item stays with that item, a comment above
+a clause stays above its keyword — and a comment that runs to the end of its
+line breaks the statement open around it. Any statement that cannot be
+proven to survive formatting unchanged is left exactly as written.
+
+## Usage
+
+```sh
+sqlc fmt [--diff]
+```
+
+Without flags, the query files are rewritten in place. With `--diff`, the
+changes are printed to standard output instead and no files are modified.
+
+## Examples
+
+Given this query file:
+
+```sql
+-- name: GetAuthor :one
+select  id,name , bio
+from   authors
+where id =  ? limit 1;
+
+-- name: SearchAuthors :many
+SELECT id, -- the primary key
+       name, bio, created_at FROM authors WHERE name LIKE ? AND bio IS NOT NULL AND id > ? AND created_at > ? AND name <> ? ORDER BY name;
+```
+
+running `sqlc fmt` rewrites it to:
+
+```sql
+-- name: GetAuthor :one
+SELECT id, name, bio
+FROM authors
+WHERE id = ?
+LIMIT 1;
+
+-- name: SearchAuthors :many
+SELECT
+  id, -- the primary key
+  name,
+  bio,
+  created_at
+FROM authors
+WHERE name LIKE ? AND bio IS NOT NULL AND id > ? AND created_at > ? AND name <> ?
+ORDER BY name;
+```
+
+`GetAuthor` keeps the line breaks its author wrote; had it been written on
+one line, it would stay on one line. In `SearchAuthors`, the line comment
+cannot share a line with the code after it, so the statement breaks open
+around it, while the `WHERE` chain — written on one line — stays on one.
diff --git a/docs/reference/cli.md b/docs/reference/cli.md
index b0cf1eb77..286467a81 100644
--- a/docs/reference/cli.md
+++ b/docs/reference/cli.md
@@ -10,6 +10,7 @@ Available Commands:
   completion  Generate the autocompletion script for the specified shell
   createdb    Create an ephemeral database
   diff        Compare the generated files to the existing files
+  fmt         Format SQL queries
   generate    Generate source code from SQL
   help        Help about any command
   init        Create an empty sqlc.yaml settings file
diff --git a/docs/toc.yaml b/docs/toc.yaml
index 4cbdbcd15..464fe334d 100644
--- a/docs/toc.yaml
+++ b/docs/toc.yaml
@@ -20,6 +20,7 @@ sections:
   - title: Commands
     pages:
       - howto/analyze.md
+      - howto/fmt.md
       - howto/generate.md
       - howto/parse.md
       - howto/push.md
diff --git a/go.mod b/go.mod
index 06691e59d..eeef23c0e 100644
--- a/go.mod
+++ b/go.mod
@@ -20,7 +20,7 @@ require (
 	github.com/spf13/pflag v1.0.10
 	github.com/sqlc-dev/doubleclick v1.0.0
 	github.com/sqlc-dev/marino v0.3.0
-	github.com/sqlc-dev/meyer v0.1.1
+	github.com/sqlc-dev/meyer v0.1.2
 	github.com/sqlc-dev/oliphant v0.1.0
 	github.com/sqlc-dev/teesql v1.1.0
 	github.com/sqlc-dev/zetajones v0.1.0
diff --git a/go.sum b/go.sum
index 104d4cb9b..069391b24 100644
--- a/go.sum
+++ b/go.sum
@@ -69,8 +69,8 @@ github.com/sqlc-dev/doubleclick v1.0.0 h1:2/OApfQ2eLgcfa/Fqs8WSMA6atH0G8j9hHbQIg
 github.com/sqlc-dev/doubleclick v1.0.0/go.mod h1:ODHRroSrk/rr5neRHlWMSRijqOak8YmNaO3VAZCNl5Y=
 github.com/sqlc-dev/marino v0.3.0 h1:e9cinBXJFFa3yRpokYNNinWvkewgd6XVDgnlG0bOmTw=
 github.com/sqlc-dev/marino v0.3.0/go.mod h1:mQxC2dgDE0DWHMb2B5jZNk7KToJuS6wnxnffBfYnq08=
-github.com/sqlc-dev/meyer v0.1.1 h1:BAeZcfgLyTnk9f90DyGEKXPrHxtgvVD/DTM6awq2kUY=
-github.com/sqlc-dev/meyer v0.1.1/go.mod h1:pS4USCRf/SLjWtaMcnTo4YrEEFKBj8CyyqlxcVUJQH8=
+github.com/sqlc-dev/meyer v0.1.2 h1:40Ng9Glnx7CTf3yOYV7jfvDIN7voIFjrStkIULS+uws=
+github.com/sqlc-dev/meyer v0.1.2/go.mod h1:pS4USCRf/SLjWtaMcnTo4YrEEFKBj8CyyqlxcVUJQH8=
 github.com/sqlc-dev/oliphant v0.1.0 h1:RAsO6BMitIzB2+swx/qzUR5nf6w4cQ1abgHIu+Fgppo=
 github.com/sqlc-dev/oliphant v0.1.0/go.mod h1:fRM/t4FutRddTIq2YCuS4O9o+2rRwSwELRvLMqtPloo=
 github.com/sqlc-dev/teesql v1.1.0 h1:3sVYQ9FGxQVcqrqQOQ27bk0aF4c4yN1H1zLL79uaSxQ=
diff --git a/internal/cmd/cmd.go b/internal/cmd/cmd.go
index 770c7c184..4b14751a5 100644
--- a/internal/cmd/cmd.go
+++ b/internal/cmd/cmd.go
@@ -43,6 +43,7 @@ func Do(args []string, stdin io.Reader, stdout io.Writer, stderr io.Writer) int
 	rootCmd.AddCommand(createDBCmd)
 	rootCmd.AddCommand(diffCmd)
 	rootCmd.AddCommand(genCmd)
+	rootCmd.AddCommand(newFmtCmd())
 	rootCmd.AddCommand(initCmd)
 	rootCmd.AddCommand(newParseCmd())
 	rootCmd.AddCommand(newAnalyzeCmd())
diff --git a/internal/cmd/fmt.go b/internal/cmd/fmt.go
new file mode 100644
index 000000000..0b76e2e89
--- /dev/null
+++ b/internal/cmd/fmt.go
@@ -0,0 +1,446 @@
+package cmd
+
+import (
+	"context"
+	"fmt"
+	"io"
+	"os"
+	"path/filepath"
+	"runtime/trace"
+	"sort"
+	"strings"
+
+	"github.com/cubicdaiya/gonp"
+	"github.com/spf13/cobra"
+
+	"github.com/sqlc-dev/sqlc/internal/config"
+	"github.com/sqlc-dev/sqlc/internal/engine/sqlite"
+	"github.com/sqlc-dev/sqlc/internal/sql/ast"
+	"github.com/sqlc-dev/sqlc/internal/sql/format"
+	"github.com/sqlc-dev/sqlc/internal/sql/sqlpath"
+)
+
+// noLineLimit renders without a maximum line width: like gofmt, fmt never
+// rewraps a line on its own. Breaks come from the author's own line breaks
+// at the boundaries the printer models, and from comments, which cannot
+// share a line with the code after them.
+const noLineLimit = 1 << 30
+
+// queryFormatter is what the fmt command needs from an engine: a parser
+// that surfaces the comments its lexer already scans (so statements and
+// comments come from one pass, and interior comments format along with
+// their statements) plus dialect-aware formatting. Comments cannot be
+// reprinted without parser support, so ParseFile is the price of admission.
+type queryFormatter interface {
+	ParseFile(io.Reader) (*ast.File, error)
+	format.Dialect
+}
+
+// newQueryFormatter returns the formatter for engines fmt supports —
+// SQLite today. An engine joins by teaching its parser to surface comments
+// (meyer's ParseFile is the template) and adding its case here.
+func newQueryFormatter(engine config.Engine) queryFormatter {
+	switch engine {
+	case config.EngineSQLite:
+		return sqlite.NewParser()
+	default:
+		return nil
+	}
+}
+
+func newFmtCmd() *cobra.Command {
+	cmd := &cobra.Command{
+		Use:   "fmt",
+		Short: "Format SQL queries",
+		Long: `Format the SQL query files referenced by the configuration file.
+
+Each query is parsed with the engine's parser and printed back in a canonical
+form, with its comments kept where they were written. A statement that cannot
+be proven to survive formatting unchanged is left exactly as written. Files
+are rewritten in place; pass --diff to print the changes to stdout instead.`,
+		RunE: func(cmd *cobra.Command, args []string) error {
+			defer trace.StartRegion(cmd.Context(), "fmt").End()
+			stderr := cmd.ErrOrStderr()
+			stdout := cmd.OutOrStdout()
+			showDiff, err := cmd.Flags().GetBool("diff")
+			if err != nil {
+				return err
+			}
+			dir, name := getConfigPath(stderr, cmd.Flag("file"))
+			output, err := Format(cmd.Context(), dir, name, &Options{
+				Env:    ParseEnv(cmd),
+				Stderr: stderr,
+			})
+			if err != nil {
+				os.Exit(1)
+			}
+
+			filenames := make([]string, 0, len(output))
+			for filename := range output {
+				filenames = append(filenames, filename)
+			}
+			sort.Strings(filenames)
+
+			for _, filename := range filenames {
+				existing, err := os.ReadFile(filename)
+				if err != nil {
+					fmt.Fprintf(stderr, "%s: %s\n", filename, err)
+					return err
+				}
+				source := output[filename]
+				if string(existing) == source {
+					continue
+				}
+				if showDiff {
+					diff := gonp.New(getLines(existing), getLines([]byte(source)))
+					diff.Compose()
+					uniHunks := filterHunks(diff.UnifiedHunks())
+					if len(uniHunks) == 0 {
+						continue
+					}
+					rel := filepath.ToSlash(strings.TrimPrefix(filename, dir))
+					fmt.Fprintf(stdout, "--- a%s\n", rel)
+					fmt.Fprintf(stdout, "+++ b%s\n", rel)
+					diff.FprintUniHunks(stdout, uniHunks)
+					continue
+				}
+				if err := os.WriteFile(filename, []byte(source), 0644); err != nil {
+					fmt.Fprintf(stderr, "%s: %s\n", filename, err)
+					return err
+				}
+			}
+			return nil
+		},
+	}
+	cmd.Flags().Bool("diff", false, "display diffs instead of rewriting files")
+	return cmd
+}
+
+// Format formats every query file referenced by the configuration with its
+// engine's SQL formatter. It returns the formatted contents of each file,
+// keyed by absolute path. Query files for engines without a formatter are
+// skipped.
+func Format(ctx context.Context, dir, filename string, o *Options) (map[string]string, error) {
+	defer trace.StartRegion(ctx, "format").End()
+	stderr := o.Stderr
+
+	configPath, conf, err := o.ReadConfig(dir, filename)
+	if err != nil {
+		return nil, err
+	}
+	base := filepath.Base(configPath)
+	if err := config.Validate(conf); err != nil {
+		fmt.Fprintf(stderr, "error validating %s: %s\n", base, err)
+		return nil, err
+	}
+
+	engines := map[string]config.Engine{}
+	var files []string
+	for _, sql := range conf.SQL {
+		joined := make([]string, 0, len(sql.Queries))
+		for _, q := range sql.Queries {
+			joined = append(joined, filepath.Join(dir, q))
+		}
+		list, err := sqlpath.Glob(joined)
+		if err != nil {
+			fmt.Fprintf(stderr, "error listing queries: %s\n", err)
+			return nil, err
+		}
+		for _, file := range list {
+			if _, ok := engines[file]; ok {
+				continue
+			}
+			engines[file] = sql.Engine
+			files = append(files, file)
+		}
+	}
+
+	output := map[string]string{}
+	unsupported := map[config.Engine]bool{}
+	for _, file := range files {
+		f := newQueryFormatter(engines[file])
+		if f == nil {
+			if !unsupported[engines[file]] {
+				unsupported[engines[file]] = true
+				fmt.Fprintf(stderr, "sqlc fmt does not yet support the %s engine; query files left unchanged\n", engines[file])
+			}
+			continue
+		}
+		rel, err := filepath.Rel(dir, file)
+		if err != nil {
+			rel = file
+		}
+		contents, err := os.ReadFile(file)
+		if err != nil {
+			fmt.Fprintf(stderr, "%s: skipped: %s\n", rel, err)
+			continue
+		}
+		formatted, err := formatQueries(f, string(contents))
+		if err != nil {
+			// Not every query file parses without the compiler's help — for
+			// example, some engines only accept sqlc.slice() after
+			// preprocessing. Leave those files as they are.
+			fmt.Fprintf(stderr, "%s: skipped: %s\n", rel, err)
+			continue
+		}
+		// File-level belt for the reprinter path: no formatting result may
+		// change the file's comments. A violation is a formatter bug; keep
+		// the file as written and say so.
+		before, err1 := f.ParseFile(strings.NewReader(string(contents)))
+		after, err2 := f.ParseFile(strings.NewReader(formatted))
+		if err1 == nil && (err2 != nil || !sameComments(before.Comments, after.Comments)) {
+			fmt.Fprintf(stderr, "%s: skipped: formatting would alter comments (this is a bug in sqlc fmt)\n", rel)
+			continue
+		}
+		output[file] = formatted
+	}
+	return output, nil
+}
+
+// formatQueries formats each statement in a query file. The comments above
+// every statement (that's where the "-- name:" annotation lives) are kept
+// as written; comments inside a statement are threaded through the printer
+// by position.
+func formatQueries(f queryFormatter, src string) (string, error) {
+	// The parser hands over statements and comments from one lexer pass;
+	// statement bodies slice the comment list by span.
+	file, err := f.ParseFile(strings.NewReader(src))
+	if err != nil {
+		return "", err
+	}
+	stmts, fileComments := file.Stmts, file.Comments
+	var blocks []string
+	prevEnd := 0
+	for _, stmt := range stmts {
+		if stmt.Raw == nil {
+			continue
+		}
+		start := stmt.Raw.StmtLocation
+		length := stmt.Raw.StmtLen
+		if length == 0 {
+			// An unterminated final statement is reported with a zero length.
+			length = len(src) - start
+		}
+		if start < 0 || start+length > len(src) {
+			return "", fmt.Errorf("statement location out of bounds")
+		}
+		// Engines differ on whether a statement's span covers the comments
+		// above it, so start each segment where the previous one ended: the
+		// gap holds nothing but the previous terminator, whitespace and
+		// comments.
+		segStart := prevEnd
+		if start < segStart {
+			segStart = start
+		}
+		if start+length <= prevEnd {
+			continue
+		}
+		prevEnd = start + length
+		seg := src[segStart : start+length]
+		segOff := segStart
+		// A comment on the same line as the previous statement's terminator
+		// belongs to that statement, not to this one's header.
+		if len(blocks) > 0 {
+			if trailing, remainder := splitTrailingComment(seg); trailing != "" {
+				blocks[len(blocks)-1] += " " + trailing
+				segOff += len(seg) - len(remainder)
+				seg = remainder
+			}
+		}
+		orig := strings.TrimSpace(strings.TrimLeft(seg, "; \t\r\n"))
+		if orig == "" {
+			continue
+		}
+		header, rest := splitLeadingComments(orig)
+		// The statement body's own file offset, so its interior comments
+		// can be sliced out of the file's comment list in the same
+		// coordinates the parser stamped on the nodes.
+		restOff := segOff + strings.Index(seg, orig) + len(orig) - len(rest)
+		var interior []ast.Comment
+		for _, c := range fileComments {
+			if c.Start >= restOff && c.End <= start+length {
+				interior = append(interior, c)
+			}
+		}
+		block := append([]string{}, header...)
+		block = append(block, formatStmt(f, stmt.Raw, rest, interior, src))
+		blocks = append(blocks, strings.Join(block, "\n"))
+	}
+	// Everything after the last statement is its terminator, whitespace and
+	// trailing comments; keep the comments.
+	tailSeg := src[prevEnd:]
+	if len(blocks) > 0 {
+		if trailing, remainder := splitTrailingComment(tailSeg); trailing != "" {
+			blocks[len(blocks)-1] += " " + trailing
+			tailSeg = remainder
+		}
+	}
+	if tail := strings.TrimSpace(strings.TrimLeft(tailSeg, "; \t\r\n")); tail != "" {
+		blocks = append(blocks, tail)
+	}
+	if len(blocks) == 0 {
+		return src, nil
+	}
+	return strings.Join(blocks, "\n\n") + "\n", nil
+}
+
+// splitTrailingComment splits a comment sitting on the same line as the
+// previous statement's terminator off the front of the text between two
+// statements, returning the comment (or "") and the remaining text.
+func splitTrailingComment(seg string) (string, string) {
+	k := 0
+	for k < len(seg) && (seg[k] == ';' || seg[k] == ' ' || seg[k] == '\t' || seg[k] == '\r') {
+		k++
+	}
+	rest := seg[k:]
+	line, _, _ := strings.Cut(rest, "\n")
+	trimmed := strings.TrimSpace(line)
+	switch {
+	case strings.HasPrefix(trimmed, "--"):
+		return trimmed, seg[k+len(line):]
+	case strings.HasPrefix(trimmed, "/*") &&
+		strings.HasSuffix(trimmed, "*/") && strings.Count(trimmed, "*/") == 1:
+		// A block comment contained on the terminator's line.
+		return trimmed, seg[k+len(line):]
+	}
+	return "", seg
+}
+
+// splitLeadingComments splits a statement's text into the comment lines above
+// it and the statement itself. Comment lines are returned with surrounding
+// whitespace trimmed (block comment continuation lines keep their leading
+// whitespace); blank lines between comments are kept.
+func splitLeadingComments(text string) ([]string, string) {
+	var header []string
+	rest := text
+	for rest != "" {
+		line, remainder, found := strings.Cut(rest, "\n")
+		trimmed := strings.TrimSpace(line)
+		if strings.HasPrefix(trimmed, "/*") && !strings.Contains(trimmed, "*/") {
+			// A block comment spanning several lines: commit it to the
+			// header only when its closing line arrives with nothing after
+			// it. Otherwise leave the whole block with the statement.
+			block := []string{trimmed}
+			blockRest := remainder
+			for closed := false; !closed; {
+				if !found || blockRest == "" {
+					return header, rest
+				}
+				var blockLine string
+				blockLine, blockRest, found = strings.Cut(blockRest, "\n")
+				if end := strings.TrimSpace(blockLine); strings.Contains(end, "*/") {
+					if !strings.HasSuffix(end, "*/") || strings.Count(end, "*/") != 1 {
+						return header, rest
+					}
+					closed = true
+				}
+				block = append(block, strings.TrimRight(blockLine, " \t\r"))
+			}
+			header = append(header, block...)
+			rest = blockRest
+			continue
+		}
+		if !isCommentLine(trimmed) {
+			break
+		}
+		header = append(header, trimmed)
+		if !found {
+			rest = ""
+			break
+		}
+		rest = remainder
+	}
+	// A statement never ends with a comment-only line here (the parser found a
+	// statement in this segment), but drop any blank lines left at the end of
+	// the header so comments sit directly above their query.
+	for len(header) > 0 && header[len(header)-1] == "" {
+		header = header[:len(header)-1]
+	}
+	return header, rest
+}
+
+func isCommentLine(line string) bool {
+	switch {
+	case line == "":
+		// A blank line between comments.
+		return true
+	case strings.HasPrefix(line, "--"):
+		return true
+	case strings.HasPrefix(line, "/*") && strings.HasSuffix(line, "*/") && strings.Count(line, "*/") == 1:
+		// A block comment contained on a single line.
+		return true
+	default:
+		return false
+	}
+}
+
+// formatStmt returns the canonical form of a single statement, or the
+// original text when formatting cannot be proven to preserve the query.
+func formatStmt(f queryFormatter, raw *ast.RawStmt, orig string, interior []ast.Comment, src string) string {
+	fallback := strings.TrimSuffix(strings.TrimSpace(orig), ";") + ";"
+	if out, ok := formatWithComments(f, raw, interior, src); ok {
+		return out
+	}
+	return fallback
+}
+
+// formatWithComments pretty-prints a statement with its interior comments
+// and proves the result faithful three ways before accepting it: every
+// comment survives (multiset equality after reparsing the output), the SQL
+// still parses as one statement, and the output is a fixed point (printing
+// the reparsed statement with its reparsed comments reproduces it).
+func formatWithComments(f queryFormatter, raw *ast.RawStmt, interior []ast.Comment, src string) (string, bool) {
+	out := prettyCommented(raw, f, interior, src)
+	if strings.TrimSpace(strings.TrimSuffix(out, ";")) == "" {
+		return "", false
+	}
+	file, err := f.ParseFile(strings.NewReader(out))
+	if err != nil || len(file.Stmts) != 1 || file.Stmts[0].Raw == nil {
+		return "", false
+	}
+	if !sameComments(interior, file.Comments) {
+		return "", false
+	}
+	again := prettyCommented(file.Stmts[0].Raw, f, file.Comments, out)
+	if !strings.EqualFold(again, out) {
+		return "", false
+	}
+	return out, true
+}
+
+// prettyCommented attaches a statement's comments to its nodes and renders
+// it, returning "" when the printer panics or fails to place every comment.
+func prettyCommented(raw *ast.RawStmt, f queryFormatter, comments []ast.Comment, src string) (out string) {
+	defer func() {
+		if r := recover(); r != nil {
+			out = ""
+		}
+	}()
+	ct := ast.AttachComments(raw, f, comments, src)
+	out = ast.PrettyWithComments(raw, f, noLineLimit, ct)
+	if !ct.Exhausted() {
+		return ""
+	}
+	return out
+}
+
+// sameComments reports whether two comment lists carry the same comment
+// texts, as multisets, ignoring surrounding whitespace.
+func sameComments(a, b []ast.Comment) bool {
+	if len(a) != len(b) {
+		return false
+	}
+	counts := make(map[string]int, len(a))
+	for _, c := range a {
+		counts[strings.TrimSpace(c.Text)]++
+	}
+	for _, c := range b {
+		counts[strings.TrimSpace(c.Text)]--
+	}
+	for _, n := range counts {
+		if n != 0 {
+			return false
+		}
+	}
+	return true
+}
diff --git a/internal/endtoend/endtoend_test.go b/internal/endtoend/endtoend_test.go
index 5c261dc7a..1196ea717 100644
--- a/internal/endtoend/endtoend_test.go
+++ b/internal/endtoend/endtoend_test.go
@@ -316,11 +316,12 @@ func TestReplay(t *testing.T) {
 					}
 				case "vet":
 					err = cmd.Vet(ctx, path, "", &opts)
-				case "parse", "analyze":
-					// These commands are config-less and flag-driven. Run them
-					// through the real CLI entry point from inside the test
-					// directory so file arguments resolve and the output stays
-					// independent of the absolute path.
+				case "parse", "analyze", "fmt":
+					// These commands are flag-driven (fmt cases pass --diff so
+					// nothing is rewritten). Run them through the real CLI
+					// entry point from inside the test directory so file
+					// arguments resolve and the output stays independent of
+					// the absolute path.
 					var stdout bytes.Buffer
 					wd, werr := os.Getwd()
 					if werr != nil {
diff --git a/internal/endtoend/fmt_test.go b/internal/endtoend/fmt_test.go
index afcf1db10..3420a8d0b 100644
--- a/internal/endtoend/fmt_test.go
+++ b/internal/endtoend/fmt_test.go
@@ -169,6 +169,12 @@ func TestFormat(t *testing.T) {
 						}
 
 						out := ast.Format(stmt.Raw, formatter)
+						// An empty rendering is the formatter's signal that
+						// the statement carries syntax the AST does not
+						// model; sqlc fmt keeps such statements as written.
+						if strings.TrimSpace(strings.TrimSuffix(strings.TrimSpace(out), ";")) == "" {
+							t.Skip("statement has no faithful rendering")
+						}
 						actual, err := fingerprint(out)
 						if err != nil {
 							t.Error(err)
diff --git a/internal/endtoend/testdata/fmt/mysql/exec.json b/internal/endtoend/testdata/fmt/mysql/exec.json
new file mode 100644
index 000000000..191cf0ccb
--- /dev/null
+++ b/internal/endtoend/testdata/fmt/mysql/exec.json
@@ -0,0 +1,5 @@
+{
+  "command": "fmt",
+  "args": ["--diff"],
+  "contexts": ["base"]
+}
diff --git a/internal/endtoend/testdata/fmt/mysql/query.sql b/internal/endtoend/testdata/fmt/mysql/query.sql
new file mode 100644
index 000000000..fa565aeb9
--- /dev/null
+++ b/internal/endtoend/testdata/fmt/mysql/query.sql
@@ -0,0 +1,15 @@
+-- name: GetAuthor :one
+select  id,name , bio from   authors
+where id =  ? limit 1;
+
+# hash comment
+-- name: ListAuthors :many
+SELECT id, name, bio FROM authors
+ORDER BY name DESC;
+
+-- name: CreateAuthor :execresult
+insert into authors (
+  name, bio
+) values (
+  ?, ?
+);
diff --git a/internal/endtoend/testdata/fmt/mysql/schema.sql b/internal/endtoend/testdata/fmt/mysql/schema.sql
new file mode 100644
index 000000000..0fb289c16
--- /dev/null
+++ b/internal/endtoend/testdata/fmt/mysql/schema.sql
@@ -0,0 +1,5 @@
+CREATE TABLE authors (
+  id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
+  name varchar(255) NOT NULL,
+  bio text
+);
diff --git a/internal/endtoend/testdata/fmt/mysql/sqlc.yaml b/internal/endtoend/testdata/fmt/mysql/sqlc.yaml
new file mode 100644
index 000000000..b843ef55e
--- /dev/null
+++ b/internal/endtoend/testdata/fmt/mysql/sqlc.yaml
@@ -0,0 +1,9 @@
+version: "2"
+sql:
+  - engine: "mysql"
+    schema: "schema.sql"
+    queries: "query.sql"
+    gen:
+      go:
+        package: "querytest"
+        out: "go"
diff --git a/internal/endtoend/testdata/fmt/mysql/stderr.txt b/internal/endtoend/testdata/fmt/mysql/stderr.txt
new file mode 100644
index 000000000..69bf0841d
--- /dev/null
+++ b/internal/endtoend/testdata/fmt/mysql/stderr.txt
@@ -0,0 +1 @@
+sqlc fmt does not yet support the mysql engine; query files left unchanged
diff --git a/internal/endtoend/testdata/fmt/mysql/stdout.txt b/internal/endtoend/testdata/fmt/mysql/stdout.txt
new file mode 100644
index 000000000..e69de29bb
diff --git a/internal/endtoend/testdata/fmt/postgresql/exec.json b/internal/endtoend/testdata/fmt/postgresql/exec.json
new file mode 100644
index 000000000..191cf0ccb
--- /dev/null
+++ b/internal/endtoend/testdata/fmt/postgresql/exec.json
@@ -0,0 +1,5 @@
+{
+  "command": "fmt",
+  "args": ["--diff"],
+  "contexts": ["base"]
+}
diff --git a/internal/endtoend/testdata/fmt/postgresql/query.sql b/internal/endtoend/testdata/fmt/postgresql/query.sql
new file mode 100644
index 000000000..a843f7647
--- /dev/null
+++ b/internal/endtoend/testdata/fmt/postgresql/query.sql
@@ -0,0 +1,30 @@
+-- name: GetAuthor :one
+select  id,name , bio
+from   authors
+where id =  $1 limit 1; -- the primary lookup
+
+/* This listing powers the admin page.
+   Keep it ordered by name so the UI stays stable. */
+-- name: ListAuthors :many
+SELECT id, name, bio FROM authors
+ORDER BY name;
+
+-- name: CreateAuthor :one
+INSERT INTO authors (
+  name, bio
+) VALUES (
+  $1, $2
+)
+RETURNING *;
+
+-- name: PickyQuery :many
+SELECT id, -- the primary key
+       name
+FROM authors
+WHERE id > $1;
+
+-- name: SearchAuthors :many
+SELECT id, name, bio, created_at FROM authors WHERE name LIKE $1 AND bio IS NOT NULL AND id > $2 AND name <> $3 ORDER BY name, id LIMIT $4;
+
+-- name: DeleteAuthor :exec
+DELETE FROM authors WHERE id = @id
diff --git a/internal/endtoend/testdata/fmt/postgresql/schema.sql b/internal/endtoend/testdata/fmt/postgresql/schema.sql
new file mode 100644
index 000000000..468ae88c5
--- /dev/null
+++ b/internal/endtoend/testdata/fmt/postgresql/schema.sql
@@ -0,0 +1,6 @@
+CREATE TABLE authors (
+  id BIGSERIAL PRIMARY KEY,
+  name text NOT NULL,
+  bio text,
+  created_at timestamptz NOT NULL DEFAULT now()
+);
diff --git a/internal/endtoend/testdata/fmt/postgresql/sqlc.yaml b/internal/endtoend/testdata/fmt/postgresql/sqlc.yaml
new file mode 100644
index 000000000..cbd1c1399
--- /dev/null
+++ b/internal/endtoend/testdata/fmt/postgresql/sqlc.yaml
@@ -0,0 +1,9 @@
+version: "2"
+sql:
+  - engine: "postgresql"
+    schema: "schema.sql"
+    queries: "query.sql"
+    gen:
+      go:
+        package: "querytest"
+        out: "go"
diff --git a/internal/endtoend/testdata/fmt/postgresql/stderr.txt b/internal/endtoend/testdata/fmt/postgresql/stderr.txt
new file mode 100644
index 000000000..4aa7068b8
--- /dev/null
+++ b/internal/endtoend/testdata/fmt/postgresql/stderr.txt
@@ -0,0 +1 @@
+sqlc fmt does not yet support the postgresql engine; query files left unchanged
diff --git a/internal/endtoend/testdata/fmt/postgresql/stdout.txt b/internal/endtoend/testdata/fmt/postgresql/stdout.txt
new file mode 100644
index 000000000..e69de29bb
diff --git a/internal/endtoend/testdata/fmt/sqlite/exec.json b/internal/endtoend/testdata/fmt/sqlite/exec.json
new file mode 100644
index 000000000..191cf0ccb
--- /dev/null
+++ b/internal/endtoend/testdata/fmt/sqlite/exec.json
@@ -0,0 +1,5 @@
+{
+  "command": "fmt",
+  "args": ["--diff"],
+  "contexts": ["base"]
+}
diff --git a/internal/endtoend/testdata/fmt/sqlite/query.sql b/internal/endtoend/testdata/fmt/sqlite/query.sql
new file mode 100644
index 000000000..eac3f3997
--- /dev/null
+++ b/internal/endtoend/testdata/fmt/sqlite/query.sql
@@ -0,0 +1,67 @@
+-- name: GetAuthor :one
+select  id,name , bio from   authors
+where id =  ? limit 1;
+
+-- name: PickyQuery :many
+SELECT id, -- the primary key
+       name,
+       -- computed downstream
+       bio
+FROM authors
+-- soft-deleted rows are filtered
+WHERE bio IS NOT NULL
+  AND id > ?;
+
+-- name: InlineBlock :many
+SELECT /* inline note */ id, name FROM authors ORDER BY name;
+
+-- name: ListAuthors :many
+SELECT id, name, bio FROM authors
+ORDER BY name;
+
+-- name: GetEvent :one
+SELECT "EventName", "order"
+FROM "Events" WHERE id = ? LIMIT 1;
+
+-- name: CountSigils :one
+SELECT count(*) FROM authors
+WHERE id <> @at_param AND id <> :colon_param AND id <> $dollar_param;
+
+-- name: TopAuthors :many
+WITH ranked AS (
+  SELECT id, name FROM authors
+)
+SELECT * FROM ranked;
+
+-- name: AddAuthor :exec
+INSERT INTO authors (name, bio)
+VALUES (?, ?);
+
+-- name: MakeScratch :exec
+CREATE TABLE scratch (
+  id INTEGER NOT NULL,
+  label TEXT
+);
+
+-- name: MakeMeasurements :exec
+CREATE TABLE IF NOT EXISTS measurements (
+  id INTEGER PRIMARY KEY,
+  label VARYING  CHARACTER(120),
+  ratio DECIMAL(10,5),
+  note
+);
+
+-- name: KeepAutoinc :exec
+CREATE TABLE   counters (id INTEGER PRIMARY KEY AUTOINCREMENT, hits INTEGER DEFAULT 0);
+
+-- name: CastLabel :one
+SELECT CAST(bio AS VARYING CHARACTER(120)) FROM authors LIMIT 1;
+
+-- name: MakeSearchIndex :exec
+CREATE  VIRTUAL  TABLE IF NOT EXISTS notes_fts USING fts5(body, tag UNINDEXED, tokenize = 'porter');
+
+-- name: MakeRecipeIndex :exec
+CREATE VIRTUAL TABLE recipes_fts USING fts5(
+  name,
+  ingredients
+);
diff --git a/internal/endtoend/testdata/fmt/sqlite/schema.sql b/internal/endtoend/testdata/fmt/sqlite/schema.sql
new file mode 100644
index 000000000..1d42f1cc1
--- /dev/null
+++ b/internal/endtoend/testdata/fmt/sqlite/schema.sql
@@ -0,0 +1,11 @@
+CREATE TABLE authors (
+  id integer PRIMARY KEY,
+  name text NOT NULL,
+  bio text
+);
+
+CREATE TABLE "Events" (
+  id integer PRIMARY KEY,
+  "EventName" text NOT NULL,
+  "order" integer NOT NULL
+);
diff --git a/internal/endtoend/testdata/fmt/sqlite/sqlc.yaml b/internal/endtoend/testdata/fmt/sqlite/sqlc.yaml
new file mode 100644
index 000000000..0b5a97a99
--- /dev/null
+++ b/internal/endtoend/testdata/fmt/sqlite/sqlc.yaml
@@ -0,0 +1,9 @@
+version: "2"
+sql:
+  - engine: "sqlite"
+    schema: "schema.sql"
+    queries: "query.sql"
+    gen:
+      go:
+        package: "querytest"
+        out: "go"
diff --git a/internal/endtoend/testdata/fmt/sqlite/stdout.txt b/internal/endtoend/testdata/fmt/sqlite/stdout.txt
new file mode 100644
index 000000000..d7572ead9
--- /dev/null
+++ b/internal/endtoend/testdata/fmt/sqlite/stdout.txt
@@ -0,0 +1,66 @@
+--- a/query.sql
++++ b/query.sql
+@@ -1,12 +1,15 @@
+ -- name: GetAuthor :one
++SELECT id, name, bio
++FROM authors
++WHERE id = ?
++LIMIT 1;
+-select  id,name , bio from   authors
+-where id =  ? limit 1;
+ 
+ -- name: PickyQuery :many
++SELECT
++  id, -- the primary key
++  name,
++  -- computed downstream
++  bio
+-SELECT id, -- the primary key
+-       name,
+-       -- computed downstream
+-       bio
+ FROM authors
+ -- soft-deleted rows are filtered
+ WHERE bio IS NOT NULL
+@@ -16,7 +19,8 @@
+ SELECT /* inline note */ id, name FROM authors ORDER BY name;
+ 
+ -- name: ListAuthors :many
++SELECT id, name, bio
++FROM authors
+-SELECT id, name, bio FROM authors
+ ORDER BY name;
+ 
+ -- name: GetEvent :one
+@@ -23,8 +27,11 @@
+ SELECT "EventName", "order"
++FROM "Events"
++WHERE id = ?
++LIMIT 1;
+-FROM "Events" WHERE id = ? LIMIT 1;
+ 
+ -- name: CountSigils :one
++SELECT count(*)
++FROM authors
+-SELECT count(*) FROM authors
+ WHERE id <> @at_param AND id <> :colon_param AND id <> $dollar_param;
+ 
+ -- name: TopAuthors :many
+@@ -46,7 +53,7 @@
+ -- name: MakeMeasurements :exec
+ CREATE TABLE IF NOT EXISTS measurements (
+   id INTEGER PRIMARY KEY,
++  label VARYING CHARACTER(120),
+-  label VARYING  CHARACTER(120),
+   ratio DECIMAL(10,5),
+   note
+ );
+@@ -58,7 +65,7 @@
+ SELECT CAST(bio AS VARYING CHARACTER(120)) FROM authors LIMIT 1;
+ 
+ -- name: MakeSearchIndex :exec
++CREATE VIRTUAL TABLE IF NOT EXISTS notes_fts USING fts5(body, tag UNINDEXED, tokenize = 'porter');
+-CREATE  VIRTUAL  TABLE IF NOT EXISTS notes_fts USING fts5(body, tag UNINDEXED, tokenize = 'porter');
+ 
+ -- name: MakeRecipeIndex :exec
+ CREATE VIRTUAL TABLE recipes_fts USING fts5(
diff --git a/internal/engine/clickhouse/format.go b/internal/engine/clickhouse/format.go
index c103c7803..997af7d41 100644
--- a/internal/engine/clickhouse/format.go
+++ b/internal/engine/clickhouse/format.go
@@ -22,12 +22,6 @@ func (p *Parser) Param(n int) string {
 	return "?"
 }
 
-// NamedParam returns the named parameter placeholder for the given name.
-// ClickHouse uses {name:Type} syntax for named parameters.
-func (p *Parser) NamedParam(name string) string {
-	return "{" + name + ":String}"
-}
-
 // Cast returns a type cast expression.
 // ClickHouse uses CAST(expr AS type) syntax, same as MySQL.
 func (p *Parser) Cast(arg, typeName string) string {
diff --git a/internal/engine/dolphin/convert.go b/internal/engine/dolphin/convert.go
index cfd83b5c4..13506ce6c 100644
--- a/internal/engine/dolphin/convert.go
+++ b/internal/engine/dolphin/convert.go
@@ -560,9 +560,28 @@ func (c *cc) convertSelectField(n *pcast.SelectField) *ast.ResTarget {
 }
 
 func (c *cc) convertSelectStmt(n *pcast.SelectStmt) *ast.SelectStmt {
+	// The ORDER BY expressions are recorded twice: bare in WindowClause,
+	// where the compiler's strict_order_by validation expects them, and
+	// wrapped in SortBy nodes in SortClause, which carries the sort
+	// direction and is what formatting prints. Both share the same
+	// converted nodes so parameter numbering stays intact.
 	windowClause := &ast.List{Items: make([]ast.Node, 0)}
-	orderByClause := c.convertOrderByClause(n.OrderBy)
-	if orderByClause != nil {
+	var sortClause *ast.List
+	if n.OrderBy != nil {
+		sortClause = &ast.List{Items: make([]ast.Node, 0)}
+		orderByClause := &ast.List{Items: []ast.Node{}}
+		for _, item := range n.OrderBy.Items {
+			expr := c.convert(item.Expr)
+			orderByClause.Items = append(orderByClause.Items, expr)
+			dir := ast.SortByDirDefault
+			if item.Desc {
+				dir = ast.SortByDirDesc
+			}
+			sortClause.Items = append(sortClause.Items, &ast.SortBy{
+				Node:      expr,
+				SortbyDir: dir,
+			})
+		}
 		windowClause.Items = append(windowClause.Items, orderByClause)
 	}
 
@@ -575,6 +594,7 @@ func (c *cc) convertSelectStmt(n *pcast.SelectStmt) *ast.SelectStmt {
 		WhereClause:  c.convert(n.Where),
 		WithClause:   c.convertWithClause(n.With),
 		WindowClause: windowClause,
+		SortClause:   sortClause,
 		Op:           op,
 		All:          all,
 	}
@@ -1242,11 +1262,20 @@ func (c *cc) convertPatternInExpr(n *pcast.PatternInExpr) ast.Node {
 }
 
 func (c *cc) convertPatternLikeExpr(n *pcast.PatternLikeOrIlikeExpr) ast.Node {
+	kind := ast.A_Expr_Kind_ILIKE
+	op := "~~*"
+	if n.IsLike {
+		kind = ast.A_Expr_Kind_LIKE
+		op = "~~"
+	}
+	if n.Not {
+		op = "!" + op
+	}
 	return &ast.A_Expr{
-		Kind: ast.A_Expr_Kind(9),
+		Kind: kind,
 		Name: &ast.List{
 			Items: []ast.Node{
-				&ast.String{Str: "~~"},
+				&ast.String{Str: op},
 			},
 		},
 		Lexpr: c.convert(n.Expr),
diff --git a/internal/engine/dolphin/format.go b/internal/engine/dolphin/format.go
index 9c6346756..458ae0236 100644
--- a/internal/engine/dolphin/format.go
+++ b/internal/engine/dolphin/format.go
@@ -29,13 +29,6 @@ func (p *Parser) Param(n int) string {
 	return "?"
 }
 
-// NamedParam returns the named parameter placeholder for the given name.
-// MySQL doesn't have native named parameters, so we use ? (positional).
-// The actual parameter names are handled by sqlc's rewrite phase.
-func (p *Parser) NamedParam(name string) string {
-	return "?"
-}
-
 // Cast returns a type cast expression.
 // MySQL uses CAST(expr AS type) syntax.
 func (p *Parser) Cast(arg, typeName string) string {
diff --git a/internal/engine/postgresql/reserved.go b/internal/engine/postgresql/reserved.go
index b03a6a7e9..25cebb16e 100644
--- a/internal/engine/postgresql/reserved.go
+++ b/internal/engine/postgresql/reserved.go
@@ -64,12 +64,6 @@ func (p *Parser) Param(n int) string {
 	return fmt.Sprintf("$%d", n)
 }
 
-// NamedParam returns the named parameter placeholder for the given name.
-// PostgreSQL/sqlc uses @name syntax.
-func (p *Parser) NamedParam(name string) string {
-	return "@" + name
-}
-
 // Cast returns a type cast expression.
 // PostgreSQL uses expr::type syntax.
 func (p *Parser) Cast(arg, typeName string) string {
diff --git a/internal/engine/sqlite/convert.go b/internal/engine/sqlite/convert.go
index 88bc27981..a4e2364e8 100644
--- a/internal/engine/sqlite/convert.go
+++ b/internal/engine/sqlite/convert.go
@@ -14,9 +14,10 @@ import (
 
 // cc converts a meyer syntax tree into sqlc's engine-independent AST. One
 // converter is used per statement; paramCount numbers the anonymous "?"
-// markers within it.
+// markers within it, and src is the source the statement was parsed from.
 type cc struct {
 	paramCount int
+	src        string
 }
 
 func todo(funcname string, n meyer.Node) *ast.TODO {
@@ -214,15 +215,21 @@ func (c *cc) convertAlterTableStmt(n *meyer.AlterTableStmt) ast.Node {
 		}
 		name := identifier(def.Name)
 		return &ast.AlterTableStmt{
-			Table: parseTableName(n.Table),
+			Table:      parseTableName(n.Table),
+			Incomplete: !representableColumn(def),
 			Cmds: &ast.List{Items: []ast.Node{
 				&ast.AlterTableCmd{
 					Name:    &name,
 					Subtype: ast.AT_AddColumn,
 					Def: &ast.ColumnDef{
-						Colname:   name,
-						TypeName:  &ast.TypeName{Name: columnTypeName(def.Type)},
-						IsNotNull: hasNotNullConstraint(def.Constraints),
+						Colname: name,
+						TypeName: &ast.TypeName{
+							Name:     columnTypeName(def.Type),
+							Spelling: typeSpelling(def.Type),
+						},
+						Typeless:   def.Type == nil,
+						IsNotNull:  hasNotNullConstraint(def.Constraints),
+						PrimaryKey: hasPrimaryKeyConstraint(def.Constraints),
 					},
 				},
 			}},
@@ -278,12 +285,24 @@ func (c *cc) convertCreateTableStmt(n *meyer.CreateTableStmt) ast.Node {
 	stmt := &ast.CreateTableStmt{
 		Name:        parseTableName(n.Name),
 		IfNotExists: n.IfNotExists,
+		// The node models none of these, so a statement carrying them has
+		// no faithful rendering and the formatter keeps it as written.
+		Incomplete: n.Temp || n.Select != nil || len(n.Constraints) > 0 || len(n.Options) > 0,
 	}
 	for _, def := range n.Columns {
+		if !representableColumn(def) {
+			stmt.Incomplete = true
+		}
 		stmt.Cols = append(stmt.Cols, &ast.ColumnDef{
-			Colname:   identifier(def.Name),
-			IsNotNull: hasNotNullConstraint(def.Constraints),
-			TypeName:  &ast.TypeName{Name: columnTypeName(def.Type)},
+			Colname:    identifier(def.Name),
+			IsNotNull:  hasNotNullConstraint(def.Constraints),
+			PrimaryKey: hasPrimaryKeyConstraint(def.Constraints),
+			TypeName: &ast.TypeName{
+				Name:     columnTypeName(def.Type),
+				Spelling: typeSpelling(def.Type),
+			},
+			Typeless: def.Type == nil,
+			Location: def.Pos(),
 		})
 	}
 	return stmt
@@ -306,6 +325,19 @@ func (c *cc) convertCreateVirtualTableFTS5(n *meyer.CreateVirtualTableStmt) ast.
 	stmt := &ast.CreateTableStmt{
 		Name:        parseTableName(n.Name),
 		IfNotExists: n.IfNotExists,
+		Using:       identifier(n.Module),
+	}
+	if n.HasArgs {
+		stmt.ModuleArgs = n.Args
+		if stmt.ModuleArgs == nil {
+			stmt.ModuleArgs = []string{}
+		}
+		// The arguments carry no spans of their own, so the author's exact
+		// breaks cannot be kept; a declaration written across lines keeps
+		// the canonical broken form instead.
+		if n.Pos() >= 0 && n.End() <= len(c.src) {
+			stmt.ModuleArgsMultiline = strings.Contains(c.src[n.Pos():n.End()], "\n")
+		}
 	}
 
 	// The module arguments of a virtual table are an arbitrary token
@@ -462,7 +494,8 @@ func (c *cc) convertColumnNames(cols []*meyer.Ident) *ast.List {
 	for _, col := range cols {
 		name := identifier(col)
 		list.Items = append(list.Items, &ast.ResTarget{
-			Name: &name,
+			Name:     &name,
+			Location: col.Pos(),
 		})
 	}
 	return list
@@ -891,9 +924,20 @@ func (c *cc) convertBindParam(n *meyer.BindParam) ast.Node {
 		}
 	default:
 		// A named parameter. sqlc carries the name through as the operand of
-		// a pseudo-operator and resolves it later.
+		// a pseudo-operator and resolves it later. The operator is the
+		// parameter's own sigil, so the formatter can print the spelling the
+		// author chose — SQLite accepts :name, @name and $name, but sqlc
+		// gives them different meanings, so they must never be rewritten
+		// into one another.
+		sigil := "@"
+		switch n.Kind {
+		case meyer.ParamColon:
+			sigil = ":"
+		case meyer.ParamDollar:
+			sigil = "$"
+		}
 		return &ast.A_Expr{
-			Name:     &ast.List{Items: []ast.Node{&ast.String{Str: "@"}}},
+			Name:     &ast.List{Items: []ast.Node{&ast.String{Str: sigil}}},
 			Rexpr:    &ast.String{Str: n.Name},
 			Location: n.Pos(),
 		}
@@ -1046,6 +1090,7 @@ func (c *cc) convertCastExpr(n *meyer.CastExpr) ast.Node {
 		Arg: c.convert(n.X),
 		TypeName: &ast.TypeName{
 			Name:        name,
+			Spelling:    typeSpelling(n.Type),
 			Names:       &ast.List{Items: []ast.Node{&ast.String{Str: strings.ToLower(name)}}},
 			ArrayBounds: &ast.List{},
 		},
diff --git a/internal/engine/sqlite/format.go b/internal/engine/sqlite/format.go
index 39ac859ca..374c23b18 100644
--- a/internal/engine/sqlite/format.go
+++ b/internal/engine/sqlite/format.go
@@ -1,13 +1,35 @@
 package sqlite
 
-// QuoteIdent returns a quoted identifier if it needs quoting.
-// SQLite uses double quotes for quoting identifiers (SQL standard),
-// though backticks are also supported for MySQL compatibility.
+import "strings"
+
+// QuoteIdent quotes an identifier when printing it bare would change what it
+// names: the parser folds unquoted identifiers to lower case, so any name
+// that is not already a plain lower-case identifier — or that collides with
+// a keyword — only survives a parse round-trip inside double quotes.
 func (p *Parser) QuoteIdent(s string) string {
-	// For now, don't quote - return as-is
+	if s == "" || p.IsReservedKeyword(s) || !plainIdent(s) {
+		return `"` + strings.ReplaceAll(s, `"`, `""`) + `"`
+	}
 	return s
 }
 
+// plainIdent reports whether s parses back as itself unquoted: ASCII
+// lower-case letters, digits and underscores, not starting with a digit.
+func plainIdent(s string) bool {
+	for i, r := range s {
+		switch {
+		case r >= 'a' && r <= 'z', r == '_':
+		case r >= '0' && r <= '9':
+			if i == 0 {
+				return false
+			}
+		default:
+			return false
+		}
+	}
+	return true
+}
+
 // TypeName returns the SQL type name for the given namespace and name.
 func (p *Parser) TypeName(ns, name string) string {
 	if ns != "" {
@@ -22,12 +44,6 @@ func (p *Parser) Param(n int) string {
 	return "?"
 }
 
-// NamedParam returns the named parameter placeholder for the given name.
-// SQLite uses :name syntax for named parameters.
-func (p *Parser) NamedParam(name string) string {
-	return ":" + name
-}
-
 // Cast returns a type cast expression.
 // SQLite uses CAST(expr AS type) syntax.
 func (p *Parser) Cast(arg, typeName string) string {
diff --git a/internal/engine/sqlite/parse.go b/internal/engine/sqlite/parse.go
index 25acfd689..325dab2cd 100644
--- a/internal/engine/sqlite/parse.go
+++ b/internal/engine/sqlite/parse.go
@@ -3,9 +3,11 @@ package sqlite
 import (
 	"errors"
 	"io"
+	"strings"
 
 	meyer "github.com/sqlc-dev/meyer/ast"
 	"github.com/sqlc-dev/meyer/parser"
+	mtoken "github.com/sqlc-dev/meyer/token"
 
 	"github.com/sqlc-dev/sqlc/internal/source"
 	"github.com/sqlc-dev/sqlc/internal/sql/ast"
@@ -26,12 +28,22 @@ type Parser struct {
 var parseOptions = parser.Options{UpdateDeleteLimit: true}
 
 func (p *Parser) Parse(r io.Reader) ([]ast.Statement, error) {
+	f, err := p.ParseFile(r)
+	if err != nil {
+		return nil, err
+	}
+	return f.Stmts, nil
+}
+
+// ParseFile parses like Parse and also carries the file's comments, taken
+// from the trivia meyer's single lexer pass produces alongside the tokens.
+func (p *Parser) ParseFile(r io.Reader) (*ast.File, error) {
 	blob, err := io.ReadAll(r)
 	if err != nil {
 		return nil, err
 	}
 	src := string(blob)
-	parsed, err := parseOptions.ParseString(src)
+	parsed, err := parseOptions.ParseFile(src)
 	if err != nil {
 		return nil, normalizeErr(err)
 	}
@@ -41,8 +53,8 @@ func (p *Parser) Parse(r io.Reader) ([]ast.Statement, error) {
 	// that a statement's extent covers the comments written above it. sqlc
 	// reads the "-- name:" annotation out of that range.
 	loc := 0
-	for _, raw := range parsed {
-		converter := &cc{}
+	for _, raw := range parsed.Stmts {
+		converter := &cc{src: src}
 		out := converter.convert(raw)
 		if _, ok := out.(*ast.TODO); !ok {
 			stmts = append(stmts, ast.Statement{
@@ -55,7 +67,36 @@ func (p *Parser) Parse(r io.Reader) ([]ast.Statement, error) {
 		}
 		loc = raw.End()
 	}
-	return stmts, nil
+
+	var comments []ast.Comment
+	for _, tr := range parsed.Trivia {
+		if tr.Kind != mtoken.COMMENT {
+			continue
+		}
+		comments = append(comments, ast.Comment{
+			Text:    strings.TrimRight(tr.Text(src), " \t\r\n"),
+			Start:   tr.Pos,
+			End:     tr.End,
+			OwnLine: ownLine(src, tr.Pos),
+		})
+	}
+	return &ast.File{Stmts: stmts, Comments: comments}, nil
+}
+
+// ownLine reports that only blank space sits between the preceding line
+// break and pos.
+func ownLine(src string, pos int) bool {
+	for j := pos - 1; j >= 0; j-- {
+		switch src[j] {
+		case '\n':
+			return true
+		case ' ', '\t', '\r':
+			continue
+		default:
+			return false
+		}
+	}
+	return true
 }
 
 // trimTerminator returns the end of stmt with its terminating semicolon, and
diff --git a/internal/engine/sqlite/utils.go b/internal/engine/sqlite/utils.go
index e81b6f3fa..3e4a03e64 100644
--- a/internal/engine/sqlite/utils.go
+++ b/internal/engine/sqlite/utils.go
@@ -76,6 +76,60 @@ func typeName(n *meyer.TypeName) string {
 	return sb.String()
 }
 
+// typeSpelling returns the type as the author wrote it — identifier tokens
+// space-joined, arguments as written — for the formatter to print back.
+// typeName folds the spaces out for catalog matching.
+func typeSpelling(n *meyer.TypeName) string {
+	if n == nil {
+		return ""
+	}
+	var sb strings.Builder
+	sb.WriteString(n.Name)
+	if len(n.Args) > 0 {
+		sb.WriteString("(")
+		sb.WriteString(strings.Join(n.Args, ","))
+		sb.WriteString(")")
+	}
+	return sb.String()
+}
+
+// representableColumn reports whether a column definition round-trips
+// through the fields ast.ColumnDef models: a plain NOT NULL, a plain
+// PRIMARY KEY, or nothing. Anything else — a named constraint, a conflict
+// clause, ASC/DESC or AUTOINCREMENT, DEFAULT, UNIQUE, CHECK, COLLATE,
+// REFERENCES, GENERATED — is parsed away, so a statement printing such a
+// column would lose it. NOT NULL next to PRIMARY KEY is also beyond the
+// node: SQLite's PRIMARY KEY does not imply NOT NULL, and the printed form
+// carries only one of the pair.
+func representableColumn(def *meyer.ColumnDef) bool {
+	var notNull, primary bool
+	for _, con := range def.Constraints {
+		switch {
+		case con.Name != nil:
+			return false
+		case con.Kind == meyer.ColumnNotNull && con.OnConflict == meyer.ConflictDefault:
+			notNull = true
+		case con.Kind == meyer.ColumnPrimaryKey && con.OnConflict == meyer.ConflictDefault &&
+			con.Order == meyer.SortDefault && !con.AutoIncrement:
+			primary = true
+		default:
+			return false
+		}
+	}
+	return !(notNull && primary)
+}
+
+// hasPrimaryKeyConstraint reports whether a column definition carries a
+// PRIMARY KEY constraint.
+func hasPrimaryKeyConstraint(constraints []*meyer.ColumnConstraint) bool {
+	for _, constraint := range constraints {
+		if constraint.Kind == meyer.ColumnPrimaryKey {
+			return true
+		}
+	}
+	return false
+}
+
 // hasNotNullConstraint reports whether a column definition guarantees a
 // value. A PRIMARY KEY implies NOT NULL for the purposes of code
 // generation, matching the behavior of the previous parser.
diff --git a/internal/sql/ast/CLAUDE.md b/internal/sql/ast/CLAUDE.md
index ee62274d6..3c5d3381c 100644
--- a/internal/sql/ast/CLAUDE.md
+++ b/internal/sql/ast/CLAUDE.md
@@ -7,16 +7,67 @@ This package defines the Abstract Syntax Tree (AST) nodes used by sqlc to repres
 ### Node Interface
 All AST nodes implement the `Node` interface with:
 - `Pos() int` - returns the source position
-- `Format(buf *TrackedBuffer)` - formats the node back to SQL
+- `Format(buf *TrackedBuffer, d format.Dialect)` - formats the node back to SQL
 
 ### TrackedBuffer
-The `TrackedBuffer` type (`pg_query.go`) handles SQL formatting with dialect-specific behavior:
+The `TrackedBuffer` type (`print.go`) handles SQL formatting with dialect-specific behavior:
 - `astFormat(node Node)` - formats any AST node
 - `join(list *List, sep string)` - joins list items with separator
 - `WriteString(s string)` - writes raw SQL
 - `QuoteIdent(name string)` - quotes identifiers (dialect-specific)
 - `TypeName(ns, name string)` - formats type names (dialect-specific)
 
+### Pretty printing
+The doc renderer lives in `ast/printer` (`printer.Buffer`), which knows
+nothing about AST nodes; `TrackedBuffer` embeds it and adds the
+AST-facing layer (`astFormat`, comment emission, anchors).
+`TrackedBuffer` records a Wadler-style document (the model behind Prettier
+and ruff): Format methods emit text plus layout tokens, and the renderer
+decides which break opportunities become newlines.
+
+- `Line()` - a space when the group fits on one line, a newline otherwise
+- `Softline()` - nothing when the group fits, a newline otherwise
+- `Group()` / `EndGroup()` - a region laid out flat when its width fits
+- `Indent()` / `EndIndent()` - one level deeper (2 spaces) after breaks
+- `Breaker()` - forces every enclosing group to break (measures as
+  infinitely wide)
+- `joinComma(list)` - joins items with `,` + `Line()`
+- `condition(node)` - clause-level AND/OR chain without outer parentheses,
+  one branch per line when broken
+
+`ast.Format(n, d)` renders on a single line (all breaks collapse);
+`ast.Pretty(n, d, width)` breaks lines to fit `width` columns. Statement
+Format methods open a group and put `Line()` before each clause keyword
+(`FROM`, `WHERE`, ...), so a statement that fits stays on one line and a
+long one breaks at clause boundaries. When adding a Format method, write
+tokens so the flat rendering is correct SQL; layout tokens are optional.
+
+The fmt command does not pass a real width: like gofmt it never rewraps
+on its own, so it prints with an effectively infinite width and defers
+to the author's line breaks instead. `AttachComments` records, for each
+emission-point marker, whether its neighbouring printed nodes sat on
+different source lines; when they did, `boundary()` emits a `Breaker()`
+there on the real print, so the group the author broke stays broken and
+everything else stays flat.
+
+### Comments
+`ast.File{Stmts, Comments}` is what a comment-surfacing parser returns
+(SQLite via meyer's ParseFile). `AttachComments(raw, d, comments, src)`
+classifies each comment once, against a dry-run of the printer: source
+positions and line numbers decide trailing (same line as the code
+before) vs leading, and each comment is attached to the emission point
+— node or clause/list boundary — where the printer will reach it. From
+then on positions are never consulted: `PrettyWithComments(n, d, width,
+table)` emits by node identity, which is what lets edited or synthetic
+trees print their comments correctly (the dave/dst model; each record
+also keeps the node the comment followed, for future rewriting tools).
+A line comment forces every enclosing group to break — `hardline` and
+`breaker` tokens measure as infinitely wide — so commented statements
+format instead of collapsing. Emission points (`beforeClause`,
+`boundary` in joinComma/condition) double as classification markers on
+the dry run, guaranteeing attach-time decisions and print-time emission
+agree.
+
 ### Dialect Interface
 Dialect-specific formatting is handled via the `Dialect` interface:
 ```go
diff --git a/internal/sql/ast/a_expr.go b/internal/sql/ast/a_expr.go
index 4e67967ba..2605db59d 100644
--- a/internal/sql/ast/a_expr.go
+++ b/internal/sql/ast/a_expr.go
@@ -1,6 +1,10 @@
 package ast
 
-import "github.com/sqlc-dev/sqlc/internal/sql/format"
+import (
+	"strings"
+
+	"github.com/sqlc-dev/sqlc/internal/sql/format"
+)
 
 type A_Expr struct {
 	Kind     A_Expr_Kind
@@ -14,23 +18,43 @@ func (n *A_Expr) Pos() int {
 	return n.Location
 }
 
-// isNamedParam returns true if this A_Expr represents a named parameter (@name)
-// and extracts the parameter name if so.
-func (n *A_Expr) isNamedParam() (string, bool) {
+// isNamedParam reports whether this A_Expr represents a named parameter,
+// returning its sigil and name. Engines encode a named parameter as a
+// prefix pseudo-operator carrying the sigil the author wrote (@name for
+// most engines; SQLite also spells :name and $name). The spellings mean
+// different things to sqlc, so the printer emits the one it was given.
+func (n *A_Expr) isNamedParam() (sigil, name string, ok bool) {
 	if n.Name == nil || len(n.Name.Items) != 1 {
-		return "", false
+		return "", "", false
 	}
-	s, ok := n.Name.Items[0].(*String)
-	if !ok || s.Str != "@" {
-		return "", false
+	s, sok := n.Name.Items[0].(*String)
+	if !sok || (s.Str != "@" && s.Str != ":" && s.Str != "$") {
+		return "", "", false
 	}
 	if set(n.Lexpr) || !set(n.Rexpr) {
-		return "", false
+		return "", "", false
+	}
+	if nameStr, sok := n.Rexpr.(*String); sok {
+		return s.Str, nameStr.Str, true
 	}
-	if nameStr, ok := n.Rexpr.(*String); ok {
-		return nameStr.Str, true
+	// Before the compiler rewrites named parameters, @name parses as the @
+	// operator applied to a bare column reference.
+	if col, sok := n.Rexpr.(*ColumnRef); sok && col.Fields != nil && len(col.Fields.Items) == 1 {
+		if f, sok := col.Fields.Items[0].(*String); sok {
+			return s.Str, f.Str, true
+		}
 	}
-	return "", false
+	return "", "", false
+}
+
+// negated returns true when the expression's operator carries the negated
+// spelling of a pattern-match operator (e.g. "!~~" for NOT LIKE).
+func (n *A_Expr) negated() bool {
+	if n.Name == nil || len(n.Name.Items) != 1 {
+		return false
+	}
+	s, ok := n.Name.Items[0].(*String)
+	return ok && strings.HasPrefix(s.Str, "!")
 }
 
 func (n *A_Expr) Format(buf *TrackedBuffer, d format.Dialect) {
@@ -39,8 +63,9 @@ func (n *A_Expr) Format(buf *TrackedBuffer, d format.Dialect) {
 	}
 
 	// Check for named parameter first (works regardless of Kind)
-	if name, ok := n.isNamedParam(); ok {
-		buf.WriteString(d.NamedParam(name))
+	if sigil, name, ok := n.isNamedParam(); ok {
+		buf.WriteString(sigil)
+		buf.WriteString(name)
 		return
 	}
 
@@ -52,11 +77,19 @@ func (n *A_Expr) Format(buf *TrackedBuffer, d format.Dialect) {
 		buf.WriteString(")")
 	case A_Expr_Kind_LIKE:
 		buf.astFormat(n.Lexpr, d)
-		buf.WriteString(" LIKE ")
+		if n.negated() {
+			buf.WriteString(" NOT LIKE ")
+		} else {
+			buf.WriteString(" LIKE ")
+		}
 		buf.astFormat(n.Rexpr, d)
 	case A_Expr_Kind_ILIKE:
 		buf.astFormat(n.Lexpr, d)
-		buf.WriteString(" ILIKE ")
+		if n.negated() {
+			buf.WriteString(" NOT ILIKE ")
+		} else {
+			buf.WriteString(" ILIKE ")
+		}
 		buf.astFormat(n.Rexpr, d)
 	case A_Expr_Kind_SIMILAR:
 		buf.astFormat(n.Lexpr, d)
diff --git a/internal/sql/ast/alter_table_stmt.go b/internal/sql/ast/alter_table_stmt.go
index 4dc88707f..afbf014b0 100644
--- a/internal/sql/ast/alter_table_stmt.go
+++ b/internal/sql/ast/alter_table_stmt.go
@@ -9,6 +9,10 @@ type AlterTableStmt struct {
 	Cmds      *List
 	MissingOk bool
 	Relkind   ObjectType
+	// Incomplete marks a statement whose source carried syntax this node
+	// does not model, such as column constraints beyond plain NOT NULL and
+	// PRIMARY KEY on an added column. No faithful rendering exists for it.
+	Incomplete bool
 }
 
 func (n *AlterTableStmt) Pos() int {
@@ -19,6 +23,12 @@ func (n *AlterTableStmt) Format(buf *TrackedBuffer, d format.Dialect) {
 	if n == nil {
 		return
 	}
+	// An incomplete statement cannot be printed back: part of its source
+	// was parsed away. Render nothing, which no verification accepts, so
+	// the formatter keeps the statement as written.
+	if n.Incomplete {
+		return
+	}
 	buf.WriteString("ALTER TABLE ")
 	buf.astFormat(n.Relation, d)
 	buf.astFormat(n.Table, d)
diff --git a/internal/sql/ast/bool_expr.go b/internal/sql/ast/bool_expr.go
index f2c0243a9..65b4af53d 100644
--- a/internal/sql/ast/bool_expr.go
+++ b/internal/sql/ast/bool_expr.go
@@ -35,15 +35,34 @@ func (n *BoolExpr) Format(buf *TrackedBuffer, d format.Dialect) {
 			buf.astFormat(n.Args.Items[0], d)
 		}
 	default:
+		var op string
+		switch n.Boolop {
+		case BoolExprTypeAnd:
+			op = "AND "
+		case BoolExprTypeOr:
+			op = "OR "
+		}
 		buf.WriteString("(")
-		if items(n.Args) {
-			switch n.Boolop {
-			case BoolExprTypeAnd:
-				buf.join(n.Args, d, " AND ")
-			case BoolExprTypeOr:
-				buf.join(n.Args, d, " OR ")
+		buf.Group()
+		buf.Indent()
+		buf.Softline()
+		if items(n.Args) && op != "" {
+			first := true
+			for _, item := range n.Args.Items {
+				if _, ok := item.(*TODO); ok {
+					continue
+				}
+				if !first {
+					buf.Line()
+					buf.WriteString(op)
+				}
+				first = false
+				buf.astFormat(item, d)
 			}
 		}
+		buf.EndIndent()
+		buf.Softline()
+		buf.EndGroup()
 		buf.WriteString(")")
 	}
 }
diff --git a/internal/sql/ast/column_def.go b/internal/sql/ast/column_def.go
index 2a1c01575..6ac6a6e0c 100644
--- a/internal/sql/ast/column_def.go
+++ b/internal/sql/ast/column_def.go
@@ -3,8 +3,12 @@ package ast
 import "github.com/sqlc-dev/sqlc/internal/sql/format"
 
 type ColumnDef struct {
-	Colname    string
+	Colname string
+	// TypeName is the column's type for the catalog. When Typeless is set
+	// the author wrote no type at all — SQLite allows it — and the column
+	// prints without one, whatever TypeName carries.
 	TypeName   *TypeName
+	Typeless   bool
 	IsNotNull  bool
 	IsUnsigned bool
 	IsArray    bool
@@ -44,8 +48,10 @@ func (n *ColumnDef) Format(buf *TrackedBuffer, d format.Dialect) {
 		return
 	}
 	buf.WriteString(n.Colname)
-	buf.WriteString(" ")
-	buf.astFormat(n.TypeName, d)
+	if !n.Typeless {
+		buf.WriteString(" ")
+		buf.astFormat(n.TypeName, d)
+	}
 	// Use IsArray from ColumnDef since TypeName.ArrayBounds may not be set
 	// (for type resolution compatibility)
 	if n.IsArray && !items(n.TypeName.ArrayBounds) {
diff --git a/internal/sql/ast/comment.go b/internal/sql/ast/comment.go
new file mode 100644
index 000000000..ea877328b
--- /dev/null
+++ b/internal/sql/ast/comment.go
@@ -0,0 +1,235 @@
+package ast
+
+import (
+	"sort"
+
+	"github.com/sqlc-dev/sqlc/internal/sql/format"
+)
+
+// File is a parsed query file: its statements together with the comments
+// the parser's lexer saw. Engines whose parsers surface their trivia — the
+// lexical channel of whitespace and comments the grammar never sees, in
+// Roslyn's terminology — return it from ParseFile, so the formatter gets
+// statements and comments from one lexer pass.
+type File struct {
+	Stmts    []Statement
+	Comments []Comment
+}
+
+// Comment is a single SQL comment, positioned by byte offsets into the
+// source the statement was parsed from — the same coordinates the engine
+// parsers stamp on nodes.
+type Comment struct {
+	// Text is the comment as written, marker included ("-- x", "/* x */").
+	Text  string
+	Start int
+	End   int
+	// OwnLine reports that only blank space preceded the comment on its
+	// line, so it leads the code after it rather than trailing the code
+	// before it.
+	OwnLine bool
+}
+
+// Line reports whether the comment runs to the end of its line (-- or #),
+// so nothing may be printed after it on the same line.
+func (c Comment) Line() bool {
+	return len(c.Text) < 2 || c.Text[0] != '/' || c.Text[1] != '*'
+}
+
+// commentRec is one attached comment: the anchor nodes on either side of it
+// in print order, and whether it trails the code before it (same source
+// line) or leads the code after it (its own line).
+//
+// The next anchor is where the printer emits the comment; the prev anchor
+// is the node the comment belongs to when the tree is edited — a trailing
+// comment travels with the node it annotates, the way dave/dst attaches
+// decorations in the Go ecosystem.
+type commentRec struct {
+	c          Comment
+	prev, next Node
+	trailing   bool
+}
+
+// CommentTable holds a statement's comments attached to its nodes. It is
+// built once by AttachComments, before any printing (or, later, editing):
+// each comment is classified against the statement's anchor nodes by source
+// position and line, and from then on positions are never consulted again —
+// the printer emits comments by node identity, which is what lets an edited
+// or synthetic tree print its comments correctly.
+type CommentTable struct {
+	recs []commentRec
+	// byNext indexes recs by their next anchor, in source order; end holds
+	// the comments with no anchor after them, which trail the statement.
+	byNext map[Node][]int
+	end    []int
+	taken  []bool
+	nTaken int
+	// breaks marks the emission points where the author broke the line:
+	// the printer keeps those breaks, gofmt-style, instead of imposing a
+	// line width.
+	breaks map[Node]bool
+}
+
+// breakAt reports whether the author broke the line at this emission point.
+func (t *CommentTable) breakAt(n Node) bool {
+	return t != nil && t.breaks[n]
+}
+
+// Exhausted reports whether every attached comment was printed.
+func (t *CommentTable) Exhausted() bool {
+	return t == nil || t.nTaken == len(t.recs)
+}
+
+// take returns and consumes the comments anchored to n, in order.
+func (t *CommentTable) take(n Node) []commentRec {
+	if t == nil || n == nil {
+		return nil
+	}
+	idxs := t.byNext[n]
+	if len(idxs) == 0 {
+		return nil
+	}
+	out := make([]commentRec, 0, len(idxs))
+	for _, i := range idxs {
+		if t.taken[i] {
+			continue
+		}
+		t.taken[i] = true
+		t.nTaken++
+		out = append(out, t.recs[i])
+	}
+	return out
+}
+
+// takeRemaining returns and consumes every comment not yet printed; the
+// statement is over, so everything left trails it.
+func (t *CommentTable) takeRemaining() []commentRec {
+	if t == nil {
+		return nil
+	}
+	var out []commentRec
+	for i := range t.recs {
+		if t.taken[i] {
+			continue
+		}
+		t.taken[i] = true
+		t.nTaken++
+		out = append(out, t.recs[i])
+	}
+	return out
+}
+
+// AttachComments classifies a statement's interior comments against its
+// nodes, producing the table the printer (and any future rewriting tool)
+// works from. Placement follows gofmt's rules, decided here once from
+// source positions and lines: a comment on the same line as the code before
+// it trails that code; any other comment leads the first node printed after
+// it; a comment after the last node trails the statement.
+func AttachComments(raw *RawStmt, d format.Dialect, comments []Comment, src string) *CommentTable {
+	anchors := collectAnchors(raw, d)
+	lines := []int{0}
+	for i := 0; i < len(src); i++ {
+		if src[i] == '\n' {
+			lines = append(lines, i+1)
+		}
+	}
+	lineOf := func(pos int) int {
+		return sort.SearchInts(lines, pos+1) - 1
+	}
+
+	table := &CommentTable{byNext: make(map[Node][]int, len(anchors))}
+	for _, c := range comments {
+		// prev: the printed node with the greatest position before the
+		// comment (for the trailing/leading call). next: the emission point
+		// for the first printed node after the comment — the node itself,
+		// or, when boundary markers immediately precede it in print order,
+		// the earliest of those markers, which is where the printer will
+		// look for this comment first.
+		var prev, next Node
+		prevPos := -1
+		for _, a := range anchors {
+			if !a.marker && a.pos < c.Start && a.pos > prevPos {
+				prev, prevPos = a.node, a.pos
+			}
+		}
+		for i, a := range anchors {
+			if a.marker || a.pos <= c.Start {
+				continue
+			}
+			j := i
+			for j > 0 && anchors[j-1].marker {
+				j--
+			}
+			next = anchors[j].node
+			break
+		}
+		rec := commentRec{
+			c:        c,
+			prev:     prev,
+			next:     next,
+			trailing: !c.OwnLine && prev != nil && lineOf(prevPos) == lineOf(c.Start),
+		}
+		table.recs = append(table.recs, rec)
+		i := len(table.recs) - 1
+		if next == nil {
+			table.end = append(table.end, i)
+		} else {
+			table.byNext[next] = append(table.byNext[next], i)
+		}
+	}
+	table.taken = make([]bool, len(table.recs))
+
+	// Record where the author broke the line: an emission point whose
+	// neighbouring printed nodes sit on different source lines. The printer
+	// keeps these breaks (and only imposes new ones for comments), so the
+	// statement's shape stays the author's.
+	table.breaks = make(map[Node]bool)
+	for i, a := range anchors {
+		if !a.marker {
+			continue
+		}
+		prevPos, nextPos := -1, -1
+		for j := i - 1; j >= 0; j-- {
+			if !anchors[j].marker {
+				prevPos = anchors[j].pos
+				break
+			}
+		}
+		for j := i + 1; j < len(anchors); j++ {
+			if !anchors[j].marker {
+				nextPos = anchors[j].pos
+				break
+			}
+		}
+		if prevPos >= 0 && nextPos >= 0 && lineOf(prevPos) != lineOf(nextPos) {
+			table.breaks[a.node] = true
+		}
+	}
+	return table
+}
+
+type anchor struct {
+	node Node
+	pos  int
+	// marker anchors are emission points (beforeClause, list boundaries)
+	// rather than printed nodes; they carry no position of their own.
+	marker bool
+}
+
+// collectAnchors renders the statement once, flat, recording every
+// positioned node in the order the printer visits them. Print order is what
+// comment emission is defined against, so classifying against it keeps the
+// attach-time decision and the print-time emission point identical.
+func collectAnchors(n Node, d format.Dialect) (out []anchor) {
+	defer func() {
+		// A formatter panic here surfaces later, on the real print; anchors
+		// collected so far still place most comments.
+		recover()
+	}()
+	tb := NewTrackedBuffer()
+	tb.anchors = &out
+	if ft, ok := n.(nodeFormatter); ok {
+		ft.Format(tb, d)
+	}
+	return out
+}
diff --git a/internal/sql/ast/common_table_expr.go b/internal/sql/ast/common_table_expr.go
index aa334167c..a9cc9d502 100644
--- a/internal/sql/ast/common_table_expr.go
+++ b/internal/sql/ast/common_table_expr.go
@@ -32,6 +32,16 @@ func (n *CommonTableExpr) Format(buf *TrackedBuffer, d format.Dialect) {
 		buf.WriteString(")")
 	}
 	buf.WriteString(" AS (")
+	buf.Group()
+	buf.Indent()
+	// The body's boundary: a comment at the top of the CTE prints here, and
+	// an author who broke the line after the parenthesis keeps the CTE — and
+	// therefore the statement around it — broken open.
+	buf.boundary(n.Ctequery)
+	buf.Softline()
 	buf.astFormat(n.Ctequery, d)
+	buf.EndIndent()
+	buf.Softline()
+	buf.EndGroup()
 	buf.WriteString(")")
 }
diff --git a/internal/sql/ast/create_table_stmt.go b/internal/sql/ast/create_table_stmt.go
index f7ab2f9f6..cd11c61fa 100644
--- a/internal/sql/ast/create_table_stmt.go
+++ b/internal/sql/ast/create_table_stmt.go
@@ -9,6 +9,25 @@ type CreateTableStmt struct {
 	ReferTable  *TableName
 	Comment     string
 	Inherits    []*TableName
+	// Using names the module of a virtual table (SQLite's CREATE VIRTUAL
+	// TABLE ... USING module(...)), and ModuleArgs carries the module's
+	// argument list as written — its grammar belongs to the module, so the
+	// arguments pass through verbatim; nil means the declaration had no
+	// argument list at all. Cols still holds the columns sqlc derives from
+	// the arguments for the catalog; the statement prints as its
+	// declaration, not as those columns.
+	Using      string
+	ModuleArgs []string
+	// ModuleArgsMultiline records that the declaration was written across
+	// lines. The arguments carry no positions, so the printer cannot keep
+	// the author's exact breaks and prints the canonical broken form — one
+	// argument per line — instead.
+	ModuleArgsMultiline bool
+	// Incomplete marks a statement whose source carried syntax this node
+	// does not model — column or table constraints beyond plain NOT NULL
+	// and PRIMARY KEY, table options, TEMP, or an AS SELECT body. No
+	// faithful rendering exists for it.
+	Incomplete bool
 }
 
 func (n *CreateTableStmt) Pos() int {
@@ -19,15 +38,67 @@ func (n *CreateTableStmt) Format(buf *TrackedBuffer, d format.Dialect) {
 	if n == nil {
 		return
 	}
+	// A virtual table prints as its declaration: the module name and the
+	// argument list as written.
+	if n.Using != "" {
+		buf.WriteString("CREATE VIRTUAL TABLE ")
+		if n.IfNotExists {
+			buf.WriteString("IF NOT EXISTS ")
+		}
+		buf.astFormat(n.Name, d)
+		buf.WriteString(" USING ")
+		buf.WriteString(n.Using)
+		if n.ModuleArgs != nil {
+			buf.WriteString("(")
+			buf.Group()
+			buf.Indent()
+			if n.ModuleArgsMultiline {
+				buf.Breaker()
+			}
+			buf.Softline()
+			for i, arg := range n.ModuleArgs {
+				if i > 0 {
+					buf.WriteString(",")
+					buf.Line()
+				}
+				buf.WriteString(arg)
+			}
+			buf.EndIndent()
+			buf.Softline()
+			buf.EndGroup()
+			buf.WriteString(")")
+		}
+		return
+	}
+	// An incomplete statement cannot be printed back: part of its source
+	// was parsed away. Render nothing, which no verification accepts, so
+	// the formatter keeps the statement as written.
+	if n.Incomplete {
+		return
+	}
 	buf.WriteString("CREATE TABLE ")
+	if n.IfNotExists {
+		buf.WriteString("IF NOT EXISTS ")
+	}
 	buf.astFormat(n.Name, d)
 
-	buf.WriteString("(")
+	buf.WriteString(" (")
+	buf.Group()
+	buf.Indent()
+	if len(n.Cols) > 0 {
+		buf.boundary(n.Cols[0])
+	}
+	buf.Softline()
 	for i, col := range n.Cols {
 		if i > 0 {
-			buf.WriteString(", ")
+			buf.WriteString(",")
+			buf.boundary(col)
+			buf.Line()
 		}
 		buf.astFormat(col, d)
 	}
+	buf.EndIndent()
+	buf.Softline()
+	buf.EndGroup()
 	buf.WriteString(")")
 }
diff --git a/internal/sql/ast/delete_stmt.go b/internal/sql/ast/delete_stmt.go
index 74683f20b..318713ad6 100644
--- a/internal/sql/ast/delete_stmt.go
+++ b/internal/sql/ast/delete_stmt.go
@@ -26,9 +26,18 @@ func (n *DeleteStmt) Format(buf *TrackedBuffer, d format.Dialect) {
 		return
 	}
 
+	buf.Group()
+	defer buf.EndGroup()
+
 	if n.WithClause != nil {
 		buf.astFormat(n.WithClause, d)
-		buf.WriteString(" ")
+		// The boundary between the WITH clause and the statement's own
+		// first keyword; the group keeps a break inside the WITH clause
+		// from forcing the statement body apart clause by clause.
+		buf.boundary(n.Relations)
+		buf.Line()
+		buf.Group()
+		defer buf.EndGroup()
 	}
 
 	buf.WriteString("DELETE ")
@@ -50,22 +59,30 @@ func (n *DeleteStmt) Format(buf *TrackedBuffer, d format.Dialect) {
 	}
 
 	if items(n.UsingClause) {
-		buf.WriteString(" USING ")
+		buf.beforeClause(n.UsingClause, d)
+		buf.Line()
+		buf.WriteString("USING ")
 		buf.join(n.UsingClause, d, ", ")
 	}
 
 	if set(n.WhereClause) {
-		buf.WriteString(" WHERE ")
-		buf.astFormat(n.WhereClause, d)
+		buf.beforeClause(n.WhereClause, d)
+		buf.Line()
+		buf.WriteString("WHERE ")
+		buf.condition(n.WhereClause, d)
 	}
 
 	if set(n.LimitCount) {
-		buf.WriteString(" LIMIT ")
+		buf.beforeClause(n.LimitCount, d)
+		buf.Line()
+		buf.WriteString("LIMIT ")
 		buf.astFormat(n.LimitCount, d)
 	}
 
 	if items(n.ReturningList) {
-		buf.WriteString(" RETURNING ")
+		buf.beforeClause(n.ReturningList, d)
+		buf.Line()
+		buf.WriteString("RETURNING ")
 		formatReturningOptions(buf, d, n.ReturningOldAlias, n.ReturningNewAlias)
 		buf.astFormat(n.ReturningList, d)
 	}
diff --git a/internal/sql/ast/insert_stmt.go b/internal/sql/ast/insert_stmt.go
index 6568deb32..6ba998841 100644
--- a/internal/sql/ast/insert_stmt.go
+++ b/internal/sql/ast/insert_stmt.go
@@ -26,9 +26,18 @@ func (n *InsertStmt) Format(buf *TrackedBuffer, d format.Dialect) {
 		return
 	}
 
+	buf.Group()
+	defer buf.EndGroup()
+
 	if n.WithClause != nil {
 		buf.astFormat(n.WithClause, d)
-		buf.WriteString(" ")
+		// The boundary between the WITH clause and the statement's own
+		// first keyword; the group keeps a break inside the WITH clause
+		// from forcing the statement body apart clause by clause.
+		buf.boundary(n.Relation)
+		buf.Line()
+		buf.Group()
+		defer buf.EndGroup()
 	}
 
 	buf.WriteString("INSERT INTO ")
@@ -37,29 +46,38 @@ func (n *InsertStmt) Format(buf *TrackedBuffer, d format.Dialect) {
 	}
 	if items(n.Cols) {
 		buf.WriteString(" (")
-		buf.astFormat(n.Cols, d)
+		buf.Group()
+		buf.Indent()
+		buf.Softline()
+		buf.joinComma(n.Cols, d)
+		buf.EndIndent()
+		buf.Softline()
+		buf.EndGroup()
 		buf.WriteString(")")
 	}
 
 	if n.DefaultValues {
 		buf.WriteString(" DEFAULT VALUES")
 	} else if set(n.SelectStmt) {
-		buf.WriteString(" ")
+		buf.beforeClause(n.SelectStmt, d)
+		buf.Line()
 		buf.astFormat(n.SelectStmt, d)
 	}
 
 	if n.OnConflictClause != nil {
-		buf.WriteString(" ")
+		buf.Line()
 		buf.astFormat(n.OnConflictClause, d)
 	}
 
 	if n.OnDuplicateKeyUpdate != nil {
-		buf.WriteString(" ")
+		buf.Line()
 		buf.astFormat(n.OnDuplicateKeyUpdate, d)
 	}
 
 	if items(n.ReturningList) {
-		buf.WriteString(" RETURNING ")
+		buf.beforeClause(n.ReturningList, d)
+		buf.Line()
+		buf.WriteString("RETURNING ")
 		formatReturningOptions(buf, d, n.ReturningOldAlias, n.ReturningNewAlias)
 		buf.astFormat(n.ReturningList, d)
 	}
diff --git a/internal/sql/ast/join_expr.go b/internal/sql/ast/join_expr.go
index 8ac059d00..c68235666 100644
--- a/internal/sql/ast/join_expr.go
+++ b/internal/sql/ast/join_expr.go
@@ -22,25 +22,27 @@ func (n *JoinExpr) Format(buf *TrackedBuffer, d format.Dialect) {
 		return
 	}
 	buf.astFormat(n.Larg, d)
+	buf.beforeClause(n.Rarg, d)
+	buf.Line()
 	if n.IsNatural {
-		buf.WriteString(" NATURAL")
+		buf.WriteString("NATURAL ")
 	}
 	switch n.Jointype {
 	case JoinTypeLeft:
-		buf.WriteString(" LEFT JOIN ")
+		buf.WriteString("LEFT JOIN ")
 	case JoinTypeRight:
-		buf.WriteString(" RIGHT JOIN ")
+		buf.WriteString("RIGHT JOIN ")
 	case JoinTypeFull:
-		buf.WriteString(" FULL JOIN ")
+		buf.WriteString("FULL JOIN ")
 	case JoinTypeInner:
 		// CROSS JOIN has no ON or USING clause
 		if !items(n.UsingClause) && !set(n.Quals) {
-			buf.WriteString(" CROSS JOIN ")
+			buf.WriteString("CROSS JOIN ")
 		} else {
-			buf.WriteString(" JOIN ")
+			buf.WriteString("JOIN ")
 		}
 	default:
-		buf.WriteString(" JOIN ")
+		buf.WriteString("JOIN ")
 	}
 	buf.astFormat(n.Rarg, d)
 	if items(n.UsingClause) {
@@ -49,6 +51,6 @@ func (n *JoinExpr) Format(buf *TrackedBuffer, d format.Dialect) {
 		buf.WriteString(")")
 	} else if set(n.Quals) {
 		buf.WriteString(" ON ")
-		buf.astFormat(n.Quals, d)
+		buf.condition(n.Quals, d)
 	}
 }
diff --git a/internal/sql/ast/print.go b/internal/sql/ast/print.go
index 87f610762..1ec48a087 100644
--- a/internal/sql/ast/print.go
+++ b/internal/sql/ast/print.go
@@ -1,9 +1,8 @@
 package ast
 
 import (
-	"strings"
-
 	"github.com/sqlc-dev/sqlc/internal/debug"
+	"github.com/sqlc-dev/sqlc/internal/sql/ast/printer"
 	"github.com/sqlc-dev/sqlc/internal/sql/format"
 )
 
@@ -11,18 +10,37 @@ type nodeFormatter interface {
 	Format(*TrackedBuffer, format.Dialect)
 }
 
+// TrackedBuffer layers AST formatting over the document renderer in
+// ast/printer: node dispatch, list joins, and comment emission. The
+// renderer itself — tokens, groups, width fitting — lives in the printer
+// package; TrackedBuffer stays here because every node's Format method
+// names it, which an ast → printer → ast import cycle would forbid.
 type TrackedBuffer struct {
-	*strings.Builder
+	*printer.Buffer
+	// ct, when set, carries the statement's interior comments attached to
+	// their anchor nodes; the buffer emits each comment when it reaches the
+	// comment's anchor. Positions were consulted once, in AttachComments —
+	// never here — so edited and synthetic trees print comments correctly.
+	ct *CommentTable
+	// anchors, when set, records every positioned node and emission point
+	// in print order instead of producing output; AttachComments uses this
+	// dry run to classify comments against the same order printing will
+	// use.
+	anchors *[]anchor
 }
 
 // NewTrackedBuffer creates a new TrackedBuffer.
 func NewTrackedBuffer() *TrackedBuffer {
-	return &TrackedBuffer{
-		Builder: new(strings.Builder),
-	}
+	return &TrackedBuffer{Buffer: &printer.Buffer{}}
 }
 
 func (t *TrackedBuffer) astFormat(n Node, d format.Dialect) {
+	if t.anchors != nil && n != nil && n.Pos() > 0 {
+		*t.anchors = append(*t.anchors, anchor{node: n, pos: n.Pos()})
+	}
+	if t.ct != nil && n != nil {
+		t.emitComments(t.ct.take(n))
+	}
 	if ft, ok := n.(nodeFormatter); ok {
 		ft.Format(t, d)
 	} else {
@@ -30,27 +48,200 @@ func (t *TrackedBuffer) astFormat(n Node, d format.Dialect) {
 	}
 }
 
+// emitComments prints attached comments at the boundary before their anchor
+// node. A trailing comment continues the line before it (a line comment
+// then forces the enclosing groups to break); an own-line or line comment
+// goes on its own line; an inline block comment stays in the flow.
+func (t *TrackedBuffer) emitComments(recs []commentRec) {
+	for _, rec := range recs {
+		switch {
+		case rec.trailing:
+			t.WriteString(" ")
+			t.WriteString(rec.c.Text)
+			if rec.c.Line() {
+				t.Breaker()
+			}
+		case rec.c.OwnLine || rec.c.Line():
+			t.Hardline()
+			t.WriteString(rec.c.Text)
+			t.Hardline()
+		default:
+			t.WriteString(rec.c.Text)
+			t.WriteString(" ")
+		}
+	}
+}
+
+// beforeClause is the emission point for comments that sit between the
+// previous clause and the one about to be printed, so they land before the
+// clause keyword. Call it before the clause's line break. During the
+// AttachComments dry run it records itself as a boundary marker, which is
+// how classification and emission are guaranteed to pick the same spot —
+// and how the author's own line break before the clause is observed and
+// kept.
+func (t *TrackedBuffer) beforeClause(n Node, d format.Dialect) {
+	t.boundary(n)
+}
+
+// boundary is a separator-adjacent emission point (before a clause, after a
+// comma, before an AND/OR): comments classified to the upcoming node print
+// here, before the separator's line break, and a line break the author
+// wrote at this boundary forces the break to stay. On the dry run it
+// records a marker instead, so classification and emission agree by
+// construction.
+func (t *TrackedBuffer) boundary(next Node) {
+	if next == nil {
+		return
+	}
+	if t.anchors != nil {
+		*t.anchors = append(*t.anchors, anchor{node: next, marker: true})
+		return
+	}
+	if t.ct != nil {
+		t.emitComments(t.ct.take(next))
+		if t.ct.breakAt(next) {
+			t.Breaker()
+		}
+	}
+}
+
+// flushRemaining prints every comment not yet printed; the statement is
+// over, so everything left trails it.
+func (t *TrackedBuffer) flushRemaining() {
+	if t.ct == nil {
+		return
+	}
+	for _, rec := range t.ct.takeRemaining() {
+		if rec.trailing {
+			t.WriteString(" ")
+			t.WriteString(rec.c.Text)
+			if rec.c.Line() {
+				t.Breaker()
+			}
+		} else {
+			t.Hardline()
+			t.WriteString(rec.c.Text)
+		}
+	}
+}
+
 func (t *TrackedBuffer) join(n *List, d format.Dialect, sep string) {
 	if n == nil {
 		return
 	}
-	for i, item := range n.Items {
+	first := true
+	for _, item := range n.Items {
 		if _, ok := item.(*TODO); ok {
 			continue
 		}
-		if i > 0 {
+		if !first {
 			t.WriteString(sep)
 		}
+		first = false
+		t.astFormat(item, d)
+	}
+}
+
+// joinComma writes the list items separated by a comma and a break
+// opportunity, so a list that fits stays on one line and a list that does
+// not puts every item on its own line. An item's trailing comment prints
+// after the comma, gofmt-style: `total, -- computed`.
+func (t *TrackedBuffer) joinComma(n *List, d format.Dialect) {
+	if n == nil {
+		return
+	}
+	items := make([]Node, 0, len(n.Items))
+	for _, item := range n.Items {
+		if _, ok := item.(*TODO); ok {
+			continue
+		}
+		items = append(items, item)
+	}
+	for i, item := range items {
+		if i > 0 {
+			t.WriteString(",")
+			t.boundary(item)
+			t.Line()
+		}
+		t.astFormat(item, d)
+	}
+}
+
+// condition formats a clause-level boolean condition (WHERE, HAVING, ON).
+// A top-level AND/OR chain is printed without the enclosing parentheses a
+// nested BoolExpr gets — the clause keyword already delimits it — and each
+// branch goes on its own line when the chain does not fit:
+//
+//	WHERE name LIKE $1
+//	  AND id > $2
+func (t *TrackedBuffer) condition(n Node, d format.Dialect) {
+	be, ok := n.(*BoolExpr)
+	if !ok || (be.Boolop != BoolExprTypeAnd && be.Boolop != BoolExprTypeOr) {
+		t.astFormat(n, d)
+		return
+	}
+	op := "AND "
+	if be.Boolop == BoolExprTypeOr {
+		op = "OR "
+	}
+	t.Group()
+	t.Indent()
+	first := true
+	t.conditionArgs(be, d, op, &first)
+	t.EndIndent()
+	t.EndGroup()
+}
+
+// conditionArgs writes the branches of an AND/OR chain, flattening nested
+// chains of the same operator (some parsers produce `a AND b AND c` as a
+// left-nested tree) so no redundant parentheses appear.
+func (t *TrackedBuffer) conditionArgs(be *BoolExpr, d format.Dialect, op string, first *bool) {
+	if be.Args == nil {
+		return
+	}
+	for _, item := range be.Args.Items {
+		if _, ok := item.(*TODO); ok {
+			continue
+		}
+		if nested, ok := item.(*BoolExpr); ok && nested.Boolop == be.Boolop {
+			t.conditionArgs(nested, d, op, first)
+			continue
+		}
+		if !*first {
+			t.boundary(item)
+			t.Line()
+			t.WriteString(op)
+		}
+		*first = false
 		t.astFormat(item, d)
 	}
 }
 
+// Format renders the node as SQL on a single line.
 func Format(n Node, d format.Dialect) string {
+	return Pretty(n, d, -1)
+}
+
+// Pretty renders the node as SQL, breaking lines so the output fits within
+// width columns where the statement's structure allows it. A negative width
+// renders everything on a single line.
+func Pretty(n Node, d format.Dialect, width int) string {
+	return PrettyWithComments(n, d, width, nil)
+}
+
+// PrettyWithComments renders the node as SQL like Pretty, emitting the
+// comments a prior AttachComments call anchored to its nodes and keeping
+// the line breaks the author wrote at the boundaries the printer models.
+// Each comment prints at the boundary before its anchor, a trailing comment
+// continues the line of the code it followed, and every comment in the
+// table is printed — anything left when the statement ends trails it.
+func PrettyWithComments(n Node, d format.Dialect, width int, ct *CommentTable) string {
 	tb := NewTrackedBuffer()
+	tb.ct = ct
 	if ft, ok := n.(nodeFormatter); ok {
 		ft.Format(tb, d)
 	}
-	return tb.String()
+	return tb.Print(width)
 }
 
 func set(n Node) bool {
@@ -58,10 +249,7 @@ func set(n Node) bool {
 		return false
 	}
 	_, ok := n.(*TODO)
-	if ok {
-		return false
-	}
-	return true
+	return !ok
 }
 
 func items(n *List) bool {
diff --git a/internal/sql/ast/printer/printer.go b/internal/sql/ast/printer/printer.go
new file mode 100644
index 000000000..69c8bbacb
--- /dev/null
+++ b/internal/sql/ast/printer/printer.go
@@ -0,0 +1,250 @@
+// Package printer implements the document renderer the SQL formatter
+// prints through: a small Wadler-style engine, the model behind Prettier
+// and ruff (via Biome's printer). Callers emit a stream of tokens — literal
+// text, break opportunities, and markers that open and close groups and
+// indented regions — and Print lays each group out on a single line when
+// its flat width fits, breaking it otherwise. The package knows nothing
+// about SQL or the AST; the ast package's TrackedBuffer embeds a Buffer and
+// layers node formatting and comment emission on top.
+package printer
+
+import (
+	"strings"
+	"unicode/utf8"
+)
+
+type tokenKind uint8
+
+const (
+	tokenText tokenKind = iota
+	// tokenLine renders as a single space when its group fits on one line
+	// and as a line break when the group is broken.
+	tokenLine
+	// tokenSoftline renders as nothing when its group fits on one line and
+	// as a line break when the group is broken.
+	tokenSoftline
+	// tokenHardline always renders a line break and forces every group
+	// containing it to break (it measures as infinitely wide). Emitted
+	// around comments, which pin the author's layout open.
+	tokenHardline
+	// tokenBreaker renders nothing but forces every group containing it to
+	// break. Emitted after a trailing line comment, whose text swallows the
+	// rest of the line, and at boundaries where the author broke the line.
+	tokenBreaker
+	tokenOpenGroup
+	tokenCloseGroup
+	tokenOpenIndent
+	tokenCloseIndent
+)
+
+// breakWidth is the measured width of tokens that force a break: wider than
+// any real line, so no group containing one ever fits.
+const breakWidth = 1 << 24
+
+// indentWidth is the number of spaces per indentation level in broken
+// (multi-line) output.
+const indentWidth = 2
+
+type token struct {
+	kind tokenKind
+	text string
+}
+
+// Buffer accumulates the document token stream.
+type Buffer struct {
+	tokens []token
+}
+
+func (t *Buffer) WriteString(s string) (int, error) {
+	if s == "" {
+		return 0, nil
+	}
+	t.tokens = append(t.tokens, token{kind: tokenText, text: s})
+	return len(s), nil
+}
+
+// Write implements io.Writer so callers can use fmt.Fprintf.
+func (t *Buffer) Write(p []byte) (int, error) {
+	return t.WriteString(string(p))
+}
+
+func (t *Buffer) WriteRune(r rune) (int, error) {
+	return t.WriteString(string(r))
+}
+
+// String renders the buffer on a single line.
+func (t *Buffer) String() string {
+	return t.Print(-1)
+}
+
+// Line marks a break opportunity between two tokens: a space when the
+// surrounding group fits on one line, a line break when it does not.
+func (t *Buffer) Line() {
+	t.tokens = append(t.tokens, token{kind: tokenLine})
+}
+
+// Softline marks a break opportunity that disappears entirely when the
+// surrounding group fits on one line.
+func (t *Buffer) Softline() {
+	t.tokens = append(t.tokens, token{kind: tokenSoftline})
+}
+
+// Hardline always renders a line break and forces every enclosing group to
+// break.
+func (t *Buffer) Hardline() {
+	t.tokens = append(t.tokens, token{kind: tokenHardline})
+}
+
+// Breaker renders nothing but forces every enclosing group to break, so the
+// next break opportunity becomes a real line break.
+func (t *Buffer) Breaker() {
+	t.tokens = append(t.tokens, token{kind: tokenBreaker})
+}
+
+// Group opens a region the renderer tries to lay out on a single line,
+// breaking it only when its flat form does not fit. Must be paired with
+// EndGroup.
+func (t *Buffer) Group() {
+	t.tokens = append(t.tokens, token{kind: tokenOpenGroup})
+}
+
+func (t *Buffer) EndGroup() {
+	t.tokens = append(t.tokens, token{kind: tokenCloseGroup})
+}
+
+// Indent opens a region printed one indentation level deeper when line
+// breaks occur inside it. Must be paired with EndIndent.
+func (t *Buffer) Indent() {
+	t.tokens = append(t.tokens, token{kind: tokenOpenIndent})
+}
+
+func (t *Buffer) EndIndent() {
+	t.tokens = append(t.tokens, token{kind: tokenCloseIndent})
+}
+
+// docNode is the tree form of the token stream: text and break tokens are
+// leaves, groups and indented regions are interior nodes.
+type docNode struct {
+	kind  tokenKind
+	text  string
+	kids  []*docNode
+	width int // flat width in runes, filled in by measure
+}
+
+// tree assembles the flat token stream into a document tree. Stray close
+// markers are ignored and unclosed regions end at the end of the stream.
+func (t *Buffer) tree() *docNode {
+	root := &docNode{kind: tokenOpenGroup}
+	stack := []*docNode{root}
+	for _, tok := range t.tokens {
+		top := stack[len(stack)-1]
+		switch tok.kind {
+		case tokenText, tokenLine, tokenSoftline, tokenHardline, tokenBreaker:
+			top.kids = append(top.kids, &docNode{kind: tok.kind, text: tok.text})
+		case tokenOpenGroup, tokenOpenIndent:
+			n := &docNode{kind: tok.kind}
+			top.kids = append(top.kids, n)
+			stack = append(stack, n)
+		case tokenCloseGroup, tokenCloseIndent:
+			if len(stack) > 1 {
+				stack = stack[:len(stack)-1]
+			}
+		}
+	}
+	return root
+}
+
+// measure computes the width of every node when rendered flat. Hardlines
+// and breakers measure wider than any real line, so no group containing one
+// ever fits — Prettier's breakParent, by arithmetic.
+func measure(d *docNode) int {
+	switch d.kind {
+	case tokenText:
+		d.width = utf8.RuneCountInString(d.text)
+	case tokenLine:
+		d.width = 1
+	case tokenSoftline:
+		d.width = 0
+	case tokenHardline, tokenBreaker:
+		d.width = breakWidth
+	default:
+		for _, kid := range d.kids {
+			d.width += measure(kid)
+			if d.width > breakWidth {
+				d.width = breakWidth
+			}
+		}
+	}
+	return d.width
+}
+
+// Print renders the token stream. A negative width renders everything on
+// one line; otherwise each group is rendered flat only when it fits in the
+// space remaining on its line — and a group holding a hardline or breaker
+// never fits, whatever the width, so forced breaks survive even an
+// unlimited line length.
+func (t *Buffer) Print(width int) string {
+	root := t.tree()
+	measure(root)
+
+	type frame struct {
+		d      *docNode
+		indent int
+		flat   bool
+	}
+	var sb strings.Builder
+	col := 0
+	// atLineStart dedupes consecutive breaks: a break that fires when the
+	// output is already at the start of a fresh line writes nothing, so a
+	// comment's surrounding hardlines collapse against clause breaks
+	// instead of leaving blank lines.
+	atLineStart := true
+	newline := func(indent int) {
+		if atLineStart {
+			return
+		}
+		sb.WriteByte('\n')
+		for i := 0; i < indent; i++ {
+			sb.WriteByte(' ')
+		}
+		col = indent
+		atLineStart = true
+	}
+	stack := []frame{{d: root, flat: width < 0}}
+	for len(stack) > 0 {
+		f := stack[len(stack)-1]
+		stack = stack[:len(stack)-1]
+		switch f.d.kind {
+		case tokenText:
+			sb.WriteString(f.d.text)
+			col += f.d.width
+			atLineStart = false
+		case tokenLine:
+			if f.flat {
+				sb.WriteByte(' ')
+				col++
+				atLineStart = false
+			} else {
+				newline(f.indent)
+			}
+		case tokenSoftline:
+			if !f.flat {
+				newline(f.indent)
+			}
+		case tokenHardline:
+			newline(f.indent)
+		case tokenBreaker:
+			// forces enclosing groups broken; renders nothing
+		case tokenOpenGroup:
+			flat := f.flat || (f.d.width < breakWidth && f.d.width <= width-col)
+			for i := len(f.d.kids) - 1; i >= 0; i-- {
+				stack = append(stack, frame{d: f.d.kids[i], indent: f.indent, flat: flat})
+			}
+		case tokenOpenIndent:
+			for i := len(f.d.kids) - 1; i >= 0; i-- {
+				stack = append(stack, frame{d: f.d.kids[i], indent: f.indent + indentWidth, flat: f.flat})
+			}
+		}
+	}
+	return sb.String()
+}
diff --git a/internal/sql/ast/raw_stmt.go b/internal/sql/ast/raw_stmt.go
index fe02bed80..619b84424 100644
--- a/internal/sql/ast/raw_stmt.go
+++ b/internal/sql/ast/raw_stmt.go
@@ -16,5 +16,7 @@ func (n *RawStmt) Format(buf *TrackedBuffer, d format.Dialect) {
 	if n.Stmt != nil {
 		buf.astFormat(n.Stmt, d)
 	}
+	// The terminator goes first: a trailing line comment would swallow it.
 	buf.WriteString(";")
+	buf.flushRemaining()
 }
diff --git a/internal/sql/ast/select_stmt.go b/internal/sql/ast/select_stmt.go
index 62e6f1c9c..2b41692bf 100644
--- a/internal/sql/ast/select_stmt.go
+++ b/internal/sql/ast/select_stmt.go
@@ -1,8 +1,6 @@
 package ast
 
 import (
-	"fmt"
-
 	"github.com/sqlc-dev/sqlc/internal/sql/format"
 )
 
@@ -44,82 +42,125 @@ func (n *SelectStmt) Format(buf *TrackedBuffer, d format.Dialect) {
 				buf.WriteString(", ")
 			}
 			buf.WriteString("(")
-			buf.astFormat(row, d)
+			buf.Group()
+			buf.Indent()
+			buf.Softline()
+			if r, ok := row.(*List); ok {
+				buf.joinComma(r, d)
+			} else {
+				buf.astFormat(row, d)
+			}
+			buf.EndIndent()
+			buf.Softline()
+			buf.EndGroup()
 			buf.WriteString(")")
 		}
 		return
 	}
 
+	buf.Group()
+	defer buf.EndGroup()
+
 	if n.WithClause != nil {
 		buf.astFormat(n.WithClause, d)
-		buf.WriteString(" ")
+		// The boundary between the WITH clause and the statement's own
+		// first keyword; the group keeps a break inside the WITH clause
+		// from forcing the statement body apart clause by clause.
+		if n.Larg != nil {
+			buf.boundary(n.Larg)
+		} else {
+			buf.boundary(n.TargetList)
+		}
+		buf.Line()
+		buf.Group()
+		defer buf.EndGroup()
 	}
 
 	if n.Larg != nil && n.Rarg != nil {
 		buf.astFormat(n.Larg, d)
+		buf.Line()
 		switch n.Op {
 		case Union:
-			buf.WriteString(" UNION ")
+			buf.WriteString("UNION")
 		case Except:
-			buf.WriteString(" EXCEPT ")
+			buf.WriteString("EXCEPT")
 		case Intersect:
-			buf.WriteString(" INTERSECT ")
+			buf.WriteString("INTERSECT")
 		}
 		if n.All {
-			buf.WriteString("ALL ")
+			buf.WriteString(" ALL")
 		}
+		buf.Line()
 		buf.astFormat(n.Rarg, d)
 	} else {
-		buf.WriteString("SELECT ")
-	}
-
-	if items(n.DistinctClause) {
-		buf.WriteString("DISTINCT ")
-		if !todo(n.DistinctClause) {
-			fmt.Fprintf(buf, "ON (")
-			buf.astFormat(n.DistinctClause, d)
-			fmt.Fprintf(buf, ")")
+		buf.WriteString("SELECT")
+		if items(n.DistinctClause) {
+			buf.WriteString(" DISTINCT")
+			if !todo(n.DistinctClause) {
+				buf.WriteString(" ON (")
+				buf.astFormat(n.DistinctClause, d)
+				buf.WriteString(")")
+			}
 		}
+		buf.Group()
+		buf.Indent()
+		buf.Line()
+		buf.joinComma(n.TargetList, d)
+		buf.EndIndent()
+		buf.EndGroup()
 	}
-	buf.astFormat(n.TargetList, d)
 
 	if items(n.FromClause) {
-		buf.WriteString(" FROM ")
+		buf.beforeClause(n.FromClause, d)
+		buf.Line()
+		buf.WriteString("FROM ")
 		buf.astFormat(n.FromClause, d)
 	}
 
 	if set(n.WhereClause) {
-		buf.WriteString(" WHERE ")
-		buf.astFormat(n.WhereClause, d)
+		buf.beforeClause(n.WhereClause, d)
+		buf.Line()
+		buf.WriteString("WHERE ")
+		buf.condition(n.WhereClause, d)
 	}
 
 	if items(n.GroupClause) {
-		buf.WriteString(" GROUP BY ")
+		buf.beforeClause(n.GroupClause, d)
+		buf.Line()
+		buf.WriteString("GROUP BY ")
 		buf.astFormat(n.GroupClause, d)
 	}
 
 	if set(n.HavingClause) {
-		buf.WriteString(" HAVING ")
-		buf.astFormat(n.HavingClause, d)
+		buf.beforeClause(n.HavingClause, d)
+		buf.Line()
+		buf.WriteString("HAVING ")
+		buf.condition(n.HavingClause, d)
 	}
 
 	if items(n.SortClause) {
-		buf.WriteString(" ORDER BY ")
+		buf.beforeClause(n.SortClause, d)
+		buf.Line()
+		buf.WriteString("ORDER BY ")
 		buf.astFormat(n.SortClause, d)
 	}
 
 	if set(n.LimitCount) {
-		buf.WriteString(" LIMIT ")
+		buf.beforeClause(n.LimitCount, d)
+		buf.Line()
+		buf.WriteString("LIMIT ")
 		buf.astFormat(n.LimitCount, d)
 	}
 
 	if set(n.LimitOffset) {
-		buf.WriteString(" OFFSET ")
+		buf.beforeClause(n.LimitOffset, d)
+		buf.Line()
+		buf.WriteString("OFFSET ")
 		buf.astFormat(n.LimitOffset, d)
 	}
 
 	if items(n.LockingClause) {
-		buf.WriteString(" ")
+		buf.Line()
 		buf.astFormat(n.LockingClause, d)
 	}
 
diff --git a/internal/sql/ast/sub_link.go b/internal/sql/ast/sub_link.go
index 99b8458af..bfd3ded20 100644
--- a/internal/sql/ast/sub_link.go
+++ b/internal/sql/ast/sub_link.go
@@ -54,6 +54,12 @@ func (n *SubLink) Format(buf *TrackedBuffer, d format.Dialect) {
 			buf.WriteString("(")
 		}
 	}
+	buf.Group()
+	buf.Indent()
+	buf.Softline()
 	buf.astFormat(n.Subselect, d)
+	buf.EndIndent()
+	buf.Softline()
+	buf.EndGroup()
 	buf.WriteString(")")
 }
diff --git a/internal/sql/ast/type_name.go b/internal/sql/ast/type_name.go
index d8d91f4f8..26ef4d6d2 100644
--- a/internal/sql/ast/type_name.go
+++ b/internal/sql/ast/type_name.go
@@ -6,6 +6,11 @@ type TypeName struct {
 	Catalog string
 	Schema  string
 	Name    string
+	// Spelling is the type as the author wrote it, when that differs from
+	// Name: SQLite folds the spaces out of multi-word type names ("VARYING
+	// CHARACTER" resolves as "VARYINGCHARACTER" in the catalog), so the
+	// formatter prints this back instead of the folded form.
+	Spelling string
 
 	// From pg.TypeName
 	Names       *List
@@ -26,6 +31,10 @@ func (n *TypeName) Format(buf *TrackedBuffer, d format.Dialect) {
 	if n == nil {
 		return
 	}
+	if n.Spelling != "" {
+		buf.WriteString(n.Spelling)
+		goto addMods
+	}
 	if items(n.Names) {
 		// Check if this is a qualified type (e.g., pg_catalog.int4)
 		if len(n.Names.Items) == 2 {
diff --git a/internal/sql/ast/update_stmt.go b/internal/sql/ast/update_stmt.go
index 54382b3f4..55775a662 100644
--- a/internal/sql/ast/update_stmt.go
+++ b/internal/sql/ast/update_stmt.go
@@ -27,9 +27,18 @@ func (n *UpdateStmt) Format(buf *TrackedBuffer, d format.Dialect) {
 	if n == nil {
 		return
 	}
+	buf.Group()
+	defer buf.EndGroup()
+
 	if n.WithClause != nil {
 		buf.astFormat(n.WithClause, d)
-		buf.WriteString(" ")
+		// The boundary between the WITH clause and the statement's own
+		// first keyword; the group keeps a break inside the WITH clause
+		// from forcing the statement body apart clause by clause.
+		buf.boundary(n.Relations)
+		buf.Line()
+		buf.Group()
+		defer buf.EndGroup()
 	}
 
 	buf.WriteString("UPDATE ")
@@ -38,7 +47,9 @@ func (n *UpdateStmt) Format(buf *TrackedBuffer, d format.Dialect) {
 	}
 
 	if items(n.TargetList) {
-		buf.WriteString(" SET ")
+		buf.beforeClause(n.TargetList, d)
+		buf.Line()
+		buf.WriteString("SET ")
 
 		multi := false
 		for _, item := range n.TargetList.Items {
@@ -79,9 +90,13 @@ func (n *UpdateStmt) Format(buf *TrackedBuffer, d format.Dialect) {
 			buf.join(vals, d, ",")
 			buf.WriteString(")")
 		} else {
+			buf.Group()
+			buf.Indent()
 			for i, item := range n.TargetList.Items {
 				if i > 0 {
-					buf.WriteString(", ")
+					buf.WriteString(",")
+					buf.boundary(item)
+					buf.Line()
 				}
 				switch nn := item.(type) {
 				case *ResTarget:
@@ -100,26 +115,36 @@ func (n *UpdateStmt) Format(buf *TrackedBuffer, d format.Dialect) {
 					buf.astFormat(item, d)
 				}
 			}
+			buf.EndIndent()
+			buf.EndGroup()
 		}
 	}
 
 	if items(n.FromClause) {
-		buf.WriteString(" FROM ")
+		buf.beforeClause(n.FromClause, d)
+		buf.Line()
+		buf.WriteString("FROM ")
 		buf.astFormat(n.FromClause, d)
 	}
 
 	if set(n.WhereClause) {
-		buf.WriteString(" WHERE ")
-		buf.astFormat(n.WhereClause, d)
+		buf.beforeClause(n.WhereClause, d)
+		buf.Line()
+		buf.WriteString("WHERE ")
+		buf.condition(n.WhereClause, d)
 	}
 
 	if set(n.LimitCount) {
-		buf.WriteString(" LIMIT ")
+		buf.beforeClause(n.LimitCount, d)
+		buf.Line()
+		buf.WriteString("LIMIT ")
 		buf.astFormat(n.LimitCount, d)
 	}
 
 	if items(n.ReturningList) {
-		buf.WriteString(" RETURNING ")
+		buf.beforeClause(n.ReturningList, d)
+		buf.Line()
+		buf.WriteString("RETURNING ")
 		formatReturningOptions(buf, d, n.ReturningOldAlias, n.ReturningNewAlias)
 		buf.astFormat(n.ReturningList, d)
 	}
diff --git a/internal/sql/ast/with_clause.go b/internal/sql/ast/with_clause.go
index 0def53d38..a7d4b2490 100644
--- a/internal/sql/ast/with_clause.go
+++ b/internal/sql/ast/with_clause.go
@@ -20,5 +20,5 @@ func (n *WithClause) Format(buf *TrackedBuffer, d format.Dialect) {
 	if n.Recursive {
 		buf.WriteString("RECURSIVE ")
 	}
-	buf.join(n.Ctes, d, ", ")
+	buf.joinComma(n.Ctes, d)
 }
diff --git a/internal/sql/format/format.go b/internal/sql/format/format.go
index b900c227e..1520cb235 100644
--- a/internal/sql/format/format.go
+++ b/internal/sql/format/format.go
@@ -14,10 +14,6 @@ type Dialect interface {
 	// PostgreSQL uses $1, $2, etc. MySQL uses ?
 	Param(n int) string
 
-	// NamedParam returns the named parameter placeholder for the given name.
-	// PostgreSQL uses @name, SQLite uses :name
-	NamedParam(name string) string
-
 	// Cast formats a type cast expression.
 	// PostgreSQL uses expr::type, MySQL uses CAST(expr AS type)
 	Cast(arg, typeName string) string