pglite-oxide 0.4.1

Embedded Postgres for Rust tests and local apps. No Docker, works with SQLx and any Postgres client.
Documentation
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
use anyhow::{Context, Result, anyhow, bail};
use serde_json::Value;
use std::collections::{HashMap, HashSet};
use std::fs;
use std::io;
use std::path::Path;
use std::path::PathBuf;
use std::sync::Arc;
use tempfile::TempDir;
#[cfg(feature = "extensions")]
use tokio::io::{AsyncWrite, AsyncWriteExt};
#[cfg(feature = "extensions")]
use tokio::runtime::Runtime;
#[cfg(feature = "extensions")]
use wasmer_wasix::virtual_net::VirtualTcpSocket;
#[cfg(feature = "extensions")]
use wasmer_wasix::virtual_net::tcp_pair::TcpSocketHalfRx;

use crate::pglite::aot;
#[cfg(feature = "extensions")]
use crate::pglite::assets;
use crate::pglite::backend::{BackendOpenKind, BackendSession};
#[cfg(feature = "extensions")]
use crate::pglite::base::install_bundled_extension_bytes;
use crate::pglite::base::{InstallOutcome, PglitePaths, RootLock};
use crate::pglite::builder::PgliteBuilder;
use crate::pglite::config::{PostgresConfig, StartupConfig};
use crate::pglite::data_dir::{DataDirArchiveFormat, dump_pgdata_archive};
use crate::pglite::errors::PgliteError;
#[cfg(feature = "extensions")]
use crate::pglite::extensions::{
    Extension, by_sql_name, extension_session_setup_sql, extension_setup_sql, resolve_extension_set,
};
use crate::pglite::interface::{
    DataTransferContainer, DescribeQueryParam, DescribeQueryResult, DescribeResultField,
    ExecProtocolOptions, ExecProtocolResult, ParserMap, QueryOptions, Results, SerializerMap,
};
use crate::pglite::parse::{parse_describe_statement_results, parse_results};
#[cfg(feature = "extensions")]
use crate::pglite::pg_dump::{PgDumpOptions, PgDumpVirtualSocket, dump_direct_sql};
#[cfg(feature = "extensions")]
use crate::pglite::postgres_mod::PostgresMod;
use crate::pglite::timing;
use crate::pglite::types::{
    ArrayTypeInfo, DEFAULT_PARSERS, DEFAULT_SERIALIZERS, TEXT, register_array_type,
};
#[cfg(feature = "extensions")]
use crate::pglite::wire::{FrontendFrameKind, FrontendFrameReader, classify_frontend_message};
use crate::protocol::messages::{BackendMessage, DatabaseError};
use crate::protocol::parser::Parser as ProtocolParser;
use crate::protocol::serializer::{BindConfig, BindValue, PortalTarget, Serialize};

type ChannelCallback = Arc<dyn Fn(&str) + Send + Sync + 'static>;
type GlobalCallback = Arc<dyn Fn(&str, &str) + Send + Sync + 'static>;

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ListenerHandle {
    channel: String,
    normalized_channel: String,
    id: u64,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct GlobalListenerHandle {
    id: u64,
}

impl ListenerHandle {
    pub fn channel(&self) -> &str {
        &self.channel
    }

    pub fn id(&self) -> u64 {
        self.id
    }
}

impl GlobalListenerHandle {
    pub fn id(&self) -> u64 {
        self.id
    }
}

struct ChannelListener {
    id: u64,
    callback: ChannelCallback,
}

struct GlobalListener {
    id: u64,
    callback: GlobalCallback,
}

/// Primary entry point for interacting with the embedded Postgres runtime.
pub struct Pglite {
    backend: BackendSession,
    _temp_dir: Option<TempDir>,
    _root_lock: Option<RootLock>,
    parser: ProtocolParser,
    serializers: SerializerMap,
    parsers: ParserMap,
    array_type_lookup_misses: HashSet<i32>,
    in_transaction: bool,
    ready: bool,
    closing: bool,
    closed: bool,
    blob_input_provided: bool,
    notify_listeners: HashMap<String, Vec<ChannelListener>>,
    global_notify_listeners: Vec<GlobalListener>,
    next_listener_id: u64,
    next_global_listener_id: u64,
}

impl Pglite {
    /// Create a builder for opening persistent or temporary PGlite databases.
    pub fn builder() -> PgliteBuilder {
        PgliteBuilder::new()
    }

    /// Open a persistent PGlite database rooted at `root`, installing and initializing it if needed.
    pub fn open(root: impl AsRef<Path>) -> Result<Self> {
        Self::builder().path(root.as_ref().to_path_buf()).open()
    }

    /// Open a persistent PGlite database under the platform data directory for `app_id`.
    pub fn open_app(app_id: (&str, &str, &str)) -> Result<Self> {
        Self::builder().app_id(app_id).open()
    }

    /// Create an ephemeral PGlite database whose files are removed when the instance is dropped.
    pub fn temporary() -> Result<Self> {
        Self::builder().temporary().open()
    }

    /// Warm the runtime module and bundled AOT artifact cache without opening a database.
    pub fn preload() -> Result<()> {
        let (temp_dir, paths) = {
            let _phase = timing::phase("preload.tempdir");
            PglitePaths::with_temp_dir()?
        };
        {
            let _phase = timing::phase("preload.runtime_module");
            crate::pglite::base::preload_runtime_module(&paths)?;
        }
        {
            let _phase = timing::phase("preload.aot_runtime");
            aot::preload_runtime_artifact()?;
        }
        drop(temp_dir);
        Ok(())
    }

    /// Warm bundled extension artifacts without permanently opening a database.
    #[cfg(feature = "extensions")]
    pub fn preload_extensions(extensions: impl IntoIterator<Item = Extension>) -> Result<()> {
        Self::preload()?;
        let extensions = extensions.into_iter().collect::<Vec<_>>();
        for extension in resolve_extension_set(&extensions)? {
            let bytes = assets::extension_archive(extension.sql_name()).ok_or_else(|| {
                anyhow!(
                    "extension asset '{}' is not bundled in this pglite-oxide build",
                    extension.sql_name()
                )
            })?;
            let (temp_dir, paths) = {
                let _phase = timing::phase("preload.extension_tempdir");
                PglitePaths::with_temp_dir()?
            };
            {
                let _phase = timing::phase("preload.extension_runtime_module");
                crate::pglite::base::preload_runtime_module(&paths)?;
            }
            {
                let _phase = timing::phase("preload.extension_archive_install");
                install_bundled_extension_bytes(&paths, extension.sql_name(), bytes)?;
            }
            {
                let _phase = timing::phase("preload.extension_side_module");
                PostgresMod::preload_extension_module_from_paths(&paths, extension)?;
            }
            {
                let _phase = timing::phase("preload.extension_aot");
                aot::preload_extension_artifact(extension)?;
            }
            drop(temp_dir);
        }
        Ok(())
    }

    /// Create a new Pglite instance backed by the provided runtime paths.
    #[doc(hidden)]
    pub fn new(paths: PglitePaths) -> Result<Self> {
        let outcome = crate::pglite::base::prepare_database_root(
            paths,
            crate::pglite::base::RootPrepareOptions::template(),
        )?;
        Self::new_prepared(outcome)
    }

    pub(crate) fn new_prepared(outcome: InstallOutcome) -> Result<Self> {
        Self::new_prepared_with_config(outcome, PostgresConfig::default(), StartupConfig::default())
    }

    pub(crate) fn new_prepared_with_config(
        outcome: InstallOutcome,
        postgres_config: PostgresConfig,
        startup_config: StartupConfig,
    ) -> Result<Self> {
        let _phase = timing::phase("pglite.open");
        let session_startup_config = startup_config.clone();
        let backend = BackendSession::open(
            outcome,
            postgres_config,
            startup_config,
            BackendOpenKind::Direct,
        )?;

        let mut instance = {
            let _phase = timing::phase("pglite.client_struct_init");
            Self {
                backend,
                _temp_dir: None,
                _root_lock: None,
                parser: ProtocolParser::new(),
                serializers: DEFAULT_SERIALIZERS.clone(),
                parsers: DEFAULT_PARSERS.clone(),
                array_type_lookup_misses: HashSet::new(),
                in_transaction: false,
                ready: true,
                closing: false,
                closed: false,
                blob_input_provided: false,
                notify_listeners: HashMap::new(),
                global_notify_listeners: Vec::new(),
                next_listener_id: 1,
                next_global_listener_id: 1,
            }
        };

        if session_startup_config.username != "postgres" {
            let sql = format!(
                "SET ROLE {}",
                crate::pglite::templating::quote_identifier(&session_startup_config.username)
            );
            instance
                .exec(&sql, None)
                .with_context(|| format!("set startup role {}", session_startup_config.username))?;
        }

        Ok(instance)
    }

    /// Install and enable a bundled Postgres extension.
    #[cfg(feature = "extensions")]
    pub fn enable_extension(&mut self, extension: Extension) -> Result<()> {
        let _phase = timing::phase("extension.enable");
        let bytes = assets::extension_archive(extension.sql_name()).ok_or_else(|| {
            anyhow!(
                "extension asset '{}' is not bundled in this pglite-oxide build",
                extension.sql_name()
            )
        })?;
        install_bundled_extension_bytes(self.paths(), extension.sql_name(), bytes)?;
        self.backend.preload_extension_module(extension)?;
        for sql in extension_setup_sql(extension) {
            self.exec(&sql, None)?;
        }
        Ok(())
    }

    #[cfg(feature = "extensions")]
    pub(crate) fn enable_preinstalled_extension(&mut self, extension: Extension) -> Result<()> {
        let _phase = timing::phase("extension.enable_preinstalled");
        self.backend.preload_installed_extension(extension)?;
        for sql in extension_session_setup_sql(extension) {
            self.exec(&sql, None)?;
        }
        Ok(())
    }

    /// Refresh direct API array parser and serializer registrations.
    ///
    /// This mirrors upstream PGlite's `refreshArrayTypes()` escape hatch. Most
    /// applications should not need it because built-in arrays are registered
    /// statically and runtime custom arrays are discovered lazily when possible.
    pub fn refresh_array_types(&mut self) -> Result<()> {
        self.check_ready()?;
        self.refresh_array_types_internal()
    }

    /// Execute a SQL query using the extended protocol.
    pub fn query(
        &mut self,
        sql: &str,
        params: &[Value],
        options: Option<&QueryOptions>,
    ) -> Result<Results> {
        self.check_ready()?;

        self.query_internal(sql, params, options)
    }

    fn query_internal(
        &mut self,
        sql: &str,
        params: &[Value],
        options: Option<&QueryOptions>,
    ) -> Result<Results> {
        let default_options = QueryOptions::default();
        let query_opts = options.unwrap_or(&default_options);

        self.handle_blob_input(query_opts.blob.as_ref())?;

        let params_snapshot: Vec<Value> = params.to_vec();
        let options_snapshot = options.cloned();
        let mut collected_messages: Vec<BackendMessage> = Vec::new();

        let mut exec_opts = ExecProtocolOptions::no_sync();
        exec_opts.on_notice = query_opts.on_notice.clone();
        exec_opts.data_transfer_container = query_opts.data_transfer_container;

        let result: Result<()> = (|| {
            let param_types = if query_opts.param_types.is_empty() {
                &[] as &[i32]
            } else {
                &query_opts.param_types
            };

            let mut messages = {
                let _phase = timing::phase("client.query.parse_describe");
                self.parse_and_describe(sql, param_types, exec_opts.clone())?
            };
            let mut data_type_ids = parse_describe_statement_results(&messages);
            if self.ensure_array_types_for_bind_values(params, &data_type_ids, query_opts)? {
                messages = {
                    let _phase = timing::phase("client.query.parse_describe_after_array_register");
                    self.parse_and_describe(sql, param_types, exec_opts.clone())?
                };
                data_type_ids = parse_describe_statement_results(&messages);
            }
            collected_messages.extend(messages);
            let bind_values = {
                let _phase = timing::phase("client.query.prepare_bind_values");
                self.prepare_bind_values(params, &data_type_ids, query_opts)?
            };
            let bind_config = BindConfig {
                values: bind_values,
                ..Default::default()
            };
            let execute_batch = {
                let _phase = timing::phase("client.query.serialize_execute");
                let mut execute_batch = Vec::new();
                execute_batch.extend(Serialize::bind(&bind_config));
                execute_batch.extend(Serialize::describe(&PortalTarget::new('P', None)));
                execute_batch.extend(Serialize::execute(None));
                execute_batch.extend(Serialize::sync());
                execute_batch
            };
            let ExecProtocolResult { messages, .. } = {
                let _phase = timing::phase("client.query.execute_roundtrip");
                self.exec_protocol(&execute_batch, exec_opts.clone())?
            };
            collected_messages.extend(messages);

            Ok(())
        })();

        if let Err(err) = result {
            match err.downcast::<DatabaseError>() {
                Ok(db_err) => {
                    let enriched = PgliteError::new(db_err, sql, params_snapshot, options_snapshot);
                    return Err(enriched.into());
                }
                Err(err) => {
                    return Err(err.context(format!("failed to execute extended query: {sql}")));
                }
            }
        }

        {
            let _phase = timing::phase("client.query.finish");
            self.finish_query(collected_messages, options)
        }
    }

    /// Return `true` if the instance is ready for new work.
    pub fn is_ready(&self) -> bool {
        self.ready && !self.closing && !self.closed
    }

    /// Return the host-side runtime and data-directory paths backing this instance.
    #[doc(hidden)]
    pub fn paths(&self) -> &PglitePaths {
        self.backend.paths()
    }

    /// Return debug-build bridge allocation/free counters for ownership tests.
    #[doc(hidden)]
    #[cfg(debug_assertions)]
    pub fn guest_bridge_allocation_counts(&self) -> (u64, u64) {
        self.backend.guest_bridge_allocation_counts()
    }

    /// Dump the physical PGDATA directory to a gzipped tar archive.
    ///
    /// The archive is intended to be loaded back into pglite-oxide/PGlite with
    /// the same PostgreSQL/PGlite version. Use [`dump_sql`](Self::dump_sql) for
    /// logical backups across versions.
    pub fn dump_data_dir(&mut self) -> Result<Vec<u8>> {
        self.dump_data_dir_with_format(DataDirArchiveFormat::TarGz)
    }

    /// Dump the physical PGDATA directory with the selected archive format.
    pub fn dump_data_dir_with_format(&mut self, format: DataDirArchiveFormat) -> Result<Vec<u8>> {
        self.check_ready()?;
        self.archive_quiesced_pgdata("dump PGDATA archive", format)
    }

    /// Clone this database into a new temporary [`Pglite`] instance.
    pub fn try_clone(&mut self) -> Result<Self> {
        #[cfg(feature = "extensions")]
        let extensions = self.bundled_extensions_in_database()?;
        let archive = self.dump_data_dir_with_format(DataDirArchiveFormat::Tar)?;
        let builder = Self::builder().temporary().load_data_dir_archive(archive);
        #[cfg(feature = "extensions")]
        let builder = builder.extensions(extensions);
        builder.open()
    }

    /// Run the bundled WASIX `pg_dump` against this database and return SQL text.
    #[cfg(feature = "extensions")]
    pub fn dump_sql(&mut self, options: PgDumpOptions) -> Result<String> {
        self.check_ready()?;
        options.validate()?;
        self.checkpoint_backend_for_physical_snapshot("direct pg_dump")?;
        self.dump_sql_via_direct_protocol(&options)
    }

    /// Run the bundled WASIX `pg_dump` and return UTF-8 SQL bytes.
    #[cfg(feature = "extensions")]
    pub fn dump_bytes(&mut self, options: PgDumpOptions) -> Result<Vec<u8>> {
        Ok(self.dump_sql(options)?.into_bytes())
    }

    fn checkpoint_backend_for_physical_snapshot(&mut self, operation: &'static str) -> Result<()> {
        if self.in_transaction {
            bail!("{operation} cannot run while a direct transaction is active");
        }
        self.exec("CHECKPOINT", None)
            .with_context(|| format!("checkpoint before {operation}"))?;
        Ok(())
    }

    fn archive_quiesced_pgdata(
        &mut self,
        operation: &'static str,
        format: DataDirArchiveFormat,
    ) -> Result<Vec<u8>> {
        self.checkpoint_backend_for_physical_snapshot(operation)?;
        self.backend
            .shutdown()
            .with_context(|| format!("quiesce backend before {operation}"))?;

        let archive = dump_pgdata_archive(
            &self.backend.paths().pgdata,
            self.backend.pgdata_template_root(),
            format,
        )
        .with_context(|| format!("materialize physical PGDATA archive for {operation}"));
        let restart = self
            .backend
            .restart()
            .and_then(|_| self.restore_session_state_after_backend_restart())
            .with_context(|| format!("restart backend after {operation}"));

        match (archive, restart) {
            (Ok(archive), Ok(())) => Ok(archive),
            (Err(err), Ok(())) => Err(err),
            (Ok(_), Err(err)) => {
                self.ready = false;
                self.closed = true;
                Err(err)
            }
            (Err(err), Err(restart_err)) => {
                self.ready = false;
                self.closed = true;
                Err(err.context(format!(
                    "backend restart after failed {operation} also failed: {restart_err:#}"
                )))
            }
        }
    }

    fn restore_session_state_after_backend_restart(&mut self) -> Result<()> {
        let username = self.backend.startup_config().username.clone();
        if username != "postgres" {
            let sql = format!(
                "SET ROLE {}",
                crate::pglite::templating::quote_identifier(&username)
            );
            self.exec(&sql, None).with_context(|| {
                format!("restore startup role {username} after backend restart")
            })?;
        }

        let channels = self
            .notify_listeners
            .iter()
            .filter(|(_, listeners)| !listeners.is_empty())
            .map(|(channel, _)| channel.clone())
            .collect::<Vec<_>>();
        for channel in channels {
            let quoted_channel = crate::pglite::templating::quote_identifier(&channel);
            self.exec_internal(&format!("LISTEN {quoted_channel}"), None)
                .with_context(|| format!("restore LISTEN {channel} after backend restart"))?;
        }
        Ok(())
    }

    #[cfg(feature = "extensions")]
    fn dump_sql_via_direct_protocol(&mut self, options: &PgDumpOptions) -> Result<String> {
        ensure_direct_pg_dump_options_match_session(self.backend.startup_config(), options)?;
        let result = dump_direct_sql(options, |socket| self.serve_direct_pg_dump_protocol(socket));
        let cleanup_result = self.cleanup_after_direct_pg_dump_session();

        match (result, cleanup_result) {
            (Ok(sql), Ok(())) => Ok(sql),
            (Err(err), Ok(())) => Err(err),
            (Ok(_), Err(err)) => Err(err),
            (Err(err), Err(cleanup_err)) => Err(err.context(format!(
                "direct pg_dump cleanup also failed: {cleanup_err:#}"
            ))),
        }
    }

    #[cfg(feature = "extensions")]
    fn cleanup_after_direct_pg_dump_session(&mut self) -> Result<()> {
        self.exec("DEALLOCATE ALL; SET search_path TO DEFAULT;", None)
            .context("reset direct pg_dump session state")?;
        Ok(())
    }

    #[cfg(feature = "extensions")]
    fn serve_direct_pg_dump_protocol(&mut self, mut socket: PgDumpVirtualSocket) -> Result<()> {
        let _ = socket.set_nodelay(true);
        let (mut socket_tx, mut socket_rx) = socket.split();
        let runtime = tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .context("create direct pg_dump virtual socket runtime")?;
        let mut reader = FrontendFrameReader::default();
        let mut buffer = [0u8; 64 * 1024];
        loop {
            let read = read_direct_pg_dump_socket(&runtime, &mut socket_rx, &mut buffer)
                .context("read direct pg_dump protocol socket")?;
            if read == 0 {
                return Ok(());
            }
            for message in reader.push(&buffer[..read])? {
                match classify_frontend_message(&message)? {
                    FrontendFrameKind::SslOrGssRequest => {
                        write_direct_pg_dump_socket(&runtime, &mut socket_tx, b"N")
                            .context("write direct pg_dump SSL refusal")?;
                    }
                    FrontendFrameKind::CancelRequest | FrontendFrameKind::Terminate => {
                        return Ok(());
                    }
                    FrontendFrameKind::Startup => {
                        if let Some(response) = self.backend.existing_startup_response() {
                            write_direct_pg_dump_socket(&runtime, &mut socket_tx, &response)
                                .context("write direct pg_dump existing startup response")?;
                        } else {
                            let response = self.backend.startup_with_packet(&message)?;
                            write_direct_pg_dump_socket(&runtime, &mut socket_tx, &response.output)
                                .context("write direct pg_dump startup response")?;
                            if !response.accepted {
                                return Ok(());
                            }
                        }
                    }
                    FrontendFrameKind::Protocol => {
                        self.exec_protocol_raw_stream(
                            &message,
                            ExecProtocolOptions::no_sync(),
                            |chunk| {
                                write_direct_pg_dump_socket(&runtime, &mut socket_tx, chunk)
                                    .context("write direct pg_dump backend protocol chunk")?;
                                Ok(())
                            },
                        )?;
                    }
                }
            }
            flush_direct_pg_dump_socket(&runtime, &mut socket_tx)
                .context("flush direct pg_dump socket")?;
        }
    }

    #[cfg(feature = "extensions")]
    fn bundled_extensions_in_database(&mut self) -> Result<Vec<Extension>> {
        let results = self.query(
            "SELECT extname FROM pg_catalog.pg_extension ORDER BY extname",
            &[],
            None,
        )?;
        let extensions = results
            .rows
            .iter()
            .filter_map(|row| row.get("extname"))
            .filter_map(|value| value.as_str())
            .filter_map(by_sql_name)
            .collect();
        Ok(extensions)
    }

    pub(crate) fn attach_temp_dir(&mut self, temp_dir: TempDir) {
        self._temp_dir = Some(temp_dir);
    }

    pub(crate) fn attach_root_lock(&mut self, root_lock: RootLock) {
        self._root_lock = Some(root_lock);
    }

    /// Return `true` if the instance has already been closed.
    pub fn is_closed(&self) -> bool {
        self.closed
    }

    /// Shut down the embedded Postgres runtime.
    pub fn close(&mut self) -> Result<()> {
        self.close_backend()
    }

    fn close_backend(&mut self) -> Result<()> {
        if self.closed {
            return Ok(());
        }
        if self.closing {
            bail!("Pglite is closing");
        }

        self.closing = true;
        let result = (|| {
            self.backend.shutdown()?;
            self.sync_to_fs()
        })();

        self.closing = false;
        if result.is_ok() {
            self.closed = true;
            self.ready = false;
            self.notify_listeners.clear();
            self.global_notify_listeners.clear();
            self._root_lock = None;
        }
        result
    }

    #[cfg(feature = "extensions")]
    pub(crate) fn close_for_template_cache(&mut self) -> Result<()> {
        self.close_backend()
    }

    /// Execute a simple SQL statement that may contain multiple commands.
    pub fn exec(&mut self, sql: &str, options: Option<&QueryOptions>) -> Result<Vec<Results>> {
        self.check_ready()?;

        self.exec_internal(sql, options)
    }

    fn exec_internal(&mut self, sql: &str, options: Option<&QueryOptions>) -> Result<Vec<Results>> {
        let options_snapshot = options.cloned();
        let default_options = QueryOptions::default();
        let exec_opts_ref = options.unwrap_or(&default_options);
        let mut exec_opts = ExecProtocolOptions::no_sync();
        exec_opts.on_notice = exec_opts_ref.on_notice.clone();
        exec_opts.data_transfer_container = exec_opts_ref.data_transfer_container;

        self.handle_blob_input(exec_opts_ref.blob.as_ref())?;

        let mut collected_messages: Vec<BackendMessage> = Vec::new();

        let message = Serialize::query(sql);
        let ExecProtocolResult { messages, .. } = match self.exec_protocol(&message, exec_opts) {
            Ok(result) => result,
            Err(err) => match err.downcast::<DatabaseError>() {
                Ok(db_err) => {
                    let enriched = PgliteError::new(db_err, sql, Vec::new(), options_snapshot);
                    return Err(enriched.into());
                }
                Err(err) => {
                    return Err(err.context(format!("failed to execute simple query: {sql}")));
                }
            },
        };
        collected_messages.extend(messages);

        self.finish_exec(collected_messages, options)
    }

    /// Register a listener for `LISTEN channel`. Returns a handle that can be used to unlisten.
    pub fn listen<F>(&mut self, channel: &str, callback: F) -> Result<ListenerHandle>
    where
        F: Fn(&str) + Send + Sync + 'static,
    {
        self.check_ready()?;

        let quoted_channel = crate::pglite::templating::quote_identifier(channel);
        let normalized = channel.to_string();
        let should_listen = match self.notify_listeners.get(&normalized) {
            Some(existing) => existing.is_empty(),
            None => true,
        };

        if should_listen {
            self.exec_internal(&format!("LISTEN {quoted_channel}"), None)?;
        }

        let callback: ChannelCallback = Arc::new(callback);
        let entry = self.notify_listeners.entry(normalized.clone()).or_default();
        let id = self.next_listener_id;
        self.next_listener_id = self.next_listener_id.wrapping_add(1);
        entry.push(ChannelListener { id, callback });

        Ok(ListenerHandle {
            channel: channel.to_string(),
            normalized_channel: normalized,
            id,
        })
    }

    /// Remove a listener corresponding to the provided handle.
    pub fn unlisten(&mut self, handle: ListenerHandle) -> Result<()> {
        if let Some(listeners) = self.notify_listeners.get_mut(&handle.normalized_channel) {
            listeners.retain(|listener| listener.id != handle.id);
            if listeners.is_empty() {
                self.notify_listeners.remove(&handle.normalized_channel);
                let quoted_channel = crate::pglite::templating::quote_identifier(&handle.channel);
                self.exec_internal(&format!("UNLISTEN {quoted_channel}"), None)?;
            }
        }
        Ok(())
    }

    /// Remove all listeners for the specified channel.
    pub fn unlisten_channel(&mut self, channel: &str) -> Result<()> {
        let quoted_channel = crate::pglite::templating::quote_identifier(channel);
        let normalized = channel.to_string();
        if self.notify_listeners.remove(&normalized).is_some() {
            self.exec_internal(&format!("UNLISTEN {quoted_channel}"), None)?;
        }
        Ok(())
    }

    /// Register a global notification callback.
    pub fn on_notification<F>(&mut self, callback: F) -> GlobalListenerHandle
    where
        F: Fn(&str, &str) + Send + Sync + 'static,
    {
        let id = self.next_global_listener_id;
        self.next_global_listener_id = self.next_global_listener_id.wrapping_add(1);
        let callback: GlobalCallback = Arc::new(callback);
        self.global_notify_listeners
            .push(GlobalListener { id, callback });
        GlobalListenerHandle { id }
    }

    /// Deregister a previously registered global notification callback.
    pub fn off_notification(&mut self, handle: GlobalListenerHandle) {
        self.global_notify_listeners
            .retain(|listener| listener.id != handle.id);
    }

    /// Describe the parameter and result metadata for a SQL query.
    pub fn describe_query(
        &mut self,
        sql: &str,
        options: Option<&QueryOptions>,
    ) -> Result<DescribeQueryResult> {
        self.check_ready()?;

        let default_options = QueryOptions::default();
        let query_opts = options.unwrap_or(&default_options);

        let options_snapshot = options.cloned();
        let mut exec_opts = ExecProtocolOptions::no_sync();
        exec_opts.on_notice = query_opts.on_notice.clone();
        exec_opts.data_transfer_container = query_opts.data_transfer_container;

        let mut describe_messages: Vec<BackendMessage> = Vec::new();

        let result: Result<()> = (|| {
            let param_types = if query_opts.param_types.is_empty() {
                &[] as &[i32]
            } else {
                &query_opts.param_types
            };

            let mut describe_batch = Vec::new();
            describe_batch.extend(Serialize::parse(None, sql, param_types));
            describe_batch.extend(Serialize::describe(&PortalTarget::new('S', None)));
            describe_batch.extend(Serialize::sync());
            let ExecProtocolResult { messages, .. } =
                self.exec_protocol(&describe_batch, exec_opts.clone())?;
            if !messages
                .iter()
                .any(|message| matches!(message, BackendMessage::ParseComplete { .. }))
            {
                bail!("extended query parse did not complete");
            }
            describe_messages.extend(messages);

            Ok(())
        })();

        if let Err(err) = result {
            match err.downcast::<DatabaseError>() {
                Ok(db_err) => {
                    let enriched = PgliteError::new(db_err, sql, Vec::new(), options_snapshot);
                    return Err(enriched.into());
                }
                Err(err) => {
                    return Err(err.context(format!("failed to describe query: {sql}")));
                }
            }
        }

        let param_type_ids = parse_describe_statement_results(&describe_messages);
        self.ensure_array_types_for_oids(param_type_ids.iter().copied(), Some(query_opts))?;
        let result_type_ids = describe_messages
            .iter()
            .filter_map(|msg| match msg {
                BackendMessage::RowDescription(desc) => Some(desc),
                _ => None,
            })
            .flat_map(|desc| desc.fields.iter().map(|field| field.data_type_id))
            .collect::<Vec<_>>();
        self.ensure_array_types_for_oids(result_type_ids.iter().copied(), Some(query_opts))?;

        let query_params = param_type_ids
            .into_iter()
            .map(|oid| DescribeQueryParam {
                data_type_id: oid,
                serializer: self.serializers.get(&oid).cloned(),
            })
            .collect();

        let result_fields = describe_messages
            .iter()
            .find_map(|msg| match msg {
                BackendMessage::RowDescription(desc) => Some(
                    desc.fields
                        .iter()
                        .map(|field| DescribeResultField {
                            name: field.name.clone(),
                            data_type_id: field.data_type_id,
                            parser: self.parsers.get(&field.data_type_id).cloned(),
                        })
                        .collect::<Vec<_>>(),
                ),
                _ => None,
            })
            .unwrap_or_default();

        Ok(DescribeQueryResult {
            query_params,
            result_fields,
        })
    }

    /// Run a closure within an SQL transaction (`BEGIN .. COMMIT/ROLLBACK`).
    pub fn transaction<F, T>(&mut self, mut callback: F) -> Result<T>
    where
        F: FnMut(&mut Transaction<'_>) -> Result<T>,
    {
        self.check_ready()?;

        // Begin transaction
        self.run_exec_command("BEGIN")?;
        self.in_transaction = true;

        let mut tx = Transaction::new(self);
        let callback_result = callback(&mut tx);

        let txn_result = match callback_result {
            Ok(value) => {
                if !tx.closed {
                    tx.commit_internal()?;
                }
                Ok(value)
            }
            Err(err) => {
                if !tx.closed {
                    tx.rollback_internal()?;
                }
                Err(err)
            }
        };

        self.in_transaction = false;
        txn_result
    }

    /// Flush runtime writes to the underlying filesystem.
    ///
    /// The WASIX backend uses host-mounted files and PostgreSQL's own fsync/WAL
    /// behavior for durability. Adding an unconditional host directory
    /// `sync_all` after every direct query is both expensive and weaker than the
    /// database's file-level fsyncs, so the Rust-level hook remains a no-op.
    pub fn sync_to_fs(&mut self) -> Result<()> {
        Ok(())
    }

    fn prepare_bind_values(
        &self,
        params: &[Value],
        data_type_ids: &[i32],
        options: &QueryOptions,
    ) -> Result<Vec<BindValue>> {
        if params.is_empty() {
            return Ok(Vec::new());
        }

        let mut values = Vec::with_capacity(params.len());
        let overrides = if options.serializers.is_empty() {
            None
        } else {
            Some(&options.serializers)
        };

        for (idx, value) in params.iter().enumerate() {
            if value.is_null() {
                values.push(BindValue::Null);
                continue;
            }

            let oid = data_type_ids.get(idx).copied().unwrap_or(TEXT);
            let serializer = overrides
                .and_then(|map| map.get(&oid))
                .or_else(|| self.serializers.get(&oid));

            let serialized = match serializer {
                Some(func) => func(value).with_context(|| {
                    format!("failed to serialize parameter {idx} using OID {oid}")
                })?,
                None => self.default_serialize_value(value),
            };

            values.push(BindValue::Text(serialized));
        }

        Ok(values)
    }

    fn parse_and_describe(
        &mut self,
        sql: &str,
        param_types: &[i32],
        exec_opts: ExecProtocolOptions,
    ) -> Result<Vec<BackendMessage>> {
        let mut prepare_batch = Vec::new();
        prepare_batch.extend(Serialize::parse(None, sql, param_types));
        prepare_batch.extend(Serialize::describe(&PortalTarget::new('S', None)));
        prepare_batch.extend(Serialize::sync());
        let ExecProtocolResult { messages, .. } = self.exec_protocol(&prepare_batch, exec_opts)?;
        if !messages
            .iter()
            .any(|message| matches!(message, BackendMessage::ParseComplete { .. }))
        {
            bail!("extended query parse did not complete");
        }
        Ok(messages)
    }

    fn default_serialize_value(&self, value: &Value) -> String {
        Self::default_serialize_value_static(value)
    }

    pub(crate) fn default_serialize_value_static(value: &Value) -> String {
        match value {
            Value::String(s) => s.clone(),
            Value::Number(num) => num.to_string(),
            Value::Bool(flag) => {
                if *flag {
                    "t".to_string()
                } else {
                    "f".to_string()
                }
            }
            _ => value.to_string(),
        }
    }

    fn finish_query(
        &mut self,
        messages: Vec<BackendMessage>,
        options: Option<&QueryOptions>,
    ) -> Result<Results> {
        let blob = {
            let _phase = timing::phase("client.finish.blob_read");
            self.get_written_blob()?
        };
        {
            let _phase = timing::phase("client.finish.blob_cleanup");
            self.cleanup_blob()?;
        }
        if !self.in_transaction {
            let _phase = timing::phase("client.finish.sync_to_fs");
            self.sync_to_fs()?;
        }
        {
            let _phase = timing::phase("client.finish.ensure_array_types");
            self.ensure_array_types_for_result_messages(&messages, options)?;
        }
        let parsed = {
            let _phase = timing::phase("client.finish.parse_results");
            parse_results(&messages, &self.parsers, options, blob)
        };
        parsed
            .into_iter()
            .next()
            .ok_or_else(|| anyhow!("query returned no result sets"))
    }

    fn finish_exec(
        &mut self,
        messages: Vec<BackendMessage>,
        options: Option<&QueryOptions>,
    ) -> Result<Vec<Results>> {
        let blob = {
            let _phase = timing::phase("client.finish.blob_read");
            self.get_written_blob()?
        };
        {
            let _phase = timing::phase("client.finish.blob_cleanup");
            self.cleanup_blob()?;
        }
        if !self.in_transaction {
            let _phase = timing::phase("client.finish.sync_to_fs");
            self.sync_to_fs()?;
        }
        {
            let _phase = timing::phase("client.finish.ensure_array_types");
            self.ensure_array_types_for_result_messages(&messages, options)?;
        }
        let parsed = {
            let _phase = timing::phase("client.finish.parse_results");
            parse_results(&messages, &self.parsers, options, blob)
        };
        Ok(parsed)
    }

    /// Execute raw PostgreSQL frontend protocol bytes and parse backend
    /// protocol messages.
    pub fn exec_protocol(
        &mut self,
        message: &[u8],
        options: ExecProtocolOptions,
    ) -> Result<ExecProtocolResult> {
        let ExecProtocolOptions {
            sync_to_fs,
            throw_on_error,
            on_notice,
            data_transfer_container,
        } = options;

        let data = {
            let _phase = timing::phase("client.protocol_roundtrip");
            self.exec_protocol_raw_inner(message, sync_to_fs, data_transfer_container)?
        };

        let mut messages = Vec::new();
        let on_notice_cb = on_notice.clone();
        let parse_result = {
            let _phase = timing::phase("client.protocol_parse");
            self.parser.parse(&data, |msg| {
                if let BackendMessage::Error(db_err) = &msg
                    && throw_on_error
                {
                    return Err(anyhow!(db_err.clone()));
                }
                if let Some(callback) = on_notice_cb.as_ref()
                    && let BackendMessage::Notice(notice) = &msg
                {
                    callback(notice);
                }
                messages.push(msg);
                Ok(())
            })
        };
        if let Err(err) = parse_result {
            match err.downcast::<DatabaseError>() {
                Ok(db_err) => {
                    self.parser = ProtocolParser::new();
                    return Err(anyhow!(db_err));
                }
                Err(err) => return Err(err),
            }
        }

        for message in &messages {
            if let BackendMessage::Notification(note) = message {
                if let Some(listeners) = self.notify_listeners.get(&note.channel) {
                    for listener in listeners {
                        (listener.callback)(&note.payload);
                    }
                }
                for listener in &self.global_notify_listeners {
                    (listener.callback)(&note.channel, &note.payload);
                }
            }
        }

        Ok(ExecProtocolResult { data, messages })
    }

    /// Execute raw PostgreSQL frontend protocol bytes and return raw backend
    /// protocol bytes.
    pub fn exec_protocol_raw(
        &mut self,
        message: &[u8],
        options: ExecProtocolOptions,
    ) -> Result<Vec<u8>> {
        self.exec_protocol_raw_inner(message, options.sync_to_fs, options.data_transfer_container)
    }

    /// Execute raw protocol bytes and pass the returned backend bytes to
    /// `on_data`.
    pub fn exec_protocol_raw_stream<F>(
        &mut self,
        message: &[u8],
        options: ExecProtocolOptions,
        mut on_data: F,
    ) -> Result<()>
    where
        F: FnMut(&[u8]) -> Result<()>,
    {
        self.backend.send_framed_raw_stream(
            message,
            options.data_transfer_container,
            &mut on_data,
        )?;
        if options.sync_to_fs {
            let _phase = timing::phase("client.protocol_stream_sync_to_fs");
            self.sync_to_fs()?;
        }
        Ok(())
    }

    fn exec_protocol_raw_inner(
        &mut self,
        message: &[u8],
        sync_to_fs: bool,
        data_transfer_container: Option<DataTransferContainer>,
    ) -> Result<Vec<u8>> {
        let data = {
            let _phase = timing::phase("client.protocol_transport_send");
            self.backend
                .send_buffered(message, data_transfer_container)?
        };
        if sync_to_fs {
            let _phase = timing::phase("client.protocol_sync_to_fs");
            self.sync_to_fs()?;
        }
        Ok(data)
    }

    fn ensure_array_types_for_bind_values(
        &mut self,
        params: &[Value],
        data_type_ids: &[i32],
        options: &QueryOptions,
    ) -> Result<bool> {
        let mut registered = false;
        for (idx, value) in params.iter().enumerate() {
            if !value.is_array() {
                continue;
            }
            let oid = data_type_ids.get(idx).copied().unwrap_or(TEXT);
            if options.serializers.contains_key(&oid) || self.serializers.contains_key(&oid) {
                continue;
            }
            registered |= self.try_register_array_type_by_array_oid(oid)?;
        }
        Ok(registered)
    }

    fn ensure_array_types_for_result_messages(
        &mut self,
        messages: &[BackendMessage],
        options: Option<&QueryOptions>,
    ) -> Result<()> {
        let oids = messages
            .iter()
            .filter_map(|msg| match msg {
                BackendMessage::RowDescription(desc) => Some(desc),
                _ => None,
            })
            .flat_map(|desc| desc.fields.iter().map(|field| field.data_type_id))
            .collect::<Vec<_>>();
        self.ensure_array_types_for_oids(oids, options)
    }

    fn ensure_array_types_for_oids(
        &mut self,
        oids: impl IntoIterator<Item = i32>,
        options: Option<&QueryOptions>,
    ) -> Result<()> {
        for oid in oids {
            if oid <= 0 || self.parsers.contains_key(&oid) {
                continue;
            }
            if options.is_some_and(|options| options.parsers.contains_key(&oid)) {
                continue;
            }
            self.try_register_array_type_by_array_oid(oid)?;
        }
        Ok(())
    }

    fn refresh_array_types_internal(&mut self) -> Result<()> {
        let sql = "
            SELECT e.oid, a.oid AS typarray, e.typdelim::text AS typdelim
            FROM pg_catalog.pg_type a
            JOIN pg_catalog.pg_type e ON e.oid = a.typelem
            WHERE a.typcategory = 'A'
              AND a.typelem <> 0
            ORDER BY e.oid
        ";
        let results = {
            let _phase = timing::phase("pglite.array_type_catalog_query");
            self.exec_internal(sql, None)?
        };
        let result_set = results
            .into_iter()
            .next()
            .ok_or_else(|| anyhow!("array type discovery returned no results"))?;

        {
            let _phase = timing::phase("pglite.array_type_register");
            for row in result_set.rows {
                if let Some(info) = array_type_info_from_row(&row) {
                    self.register_array_type(info);
                }
            }
        }
        Ok(())
    }

    fn try_register_array_type_by_array_oid(&mut self, array_oid: i32) -> Result<bool> {
        if array_oid <= 0
            || self.parsers.contains_key(&array_oid)
            || self.array_type_lookup_misses.contains(&array_oid)
        {
            return Ok(false);
        }

        let sql = format!(
            "SELECT e.oid, a.oid AS typarray, e.typdelim::text AS typdelim \
             FROM pg_catalog.pg_type a \
             JOIN pg_catalog.pg_type e ON e.oid = a.typelem \
             WHERE a.oid = {array_oid}::oid \
               AND a.typcategory = 'A' \
               AND a.typelem <> 0"
        );
        let results = {
            let _phase = timing::phase("pglite.array_type_targeted_lookup");
            self.exec_internal(&sql, None)?
        };
        let Some(result_set) = results.into_iter().next() else {
            self.array_type_lookup_misses.insert(array_oid);
            return Ok(false);
        };
        let Some(row) = result_set.rows.into_iter().next() else {
            self.array_type_lookup_misses.insert(array_oid);
            return Ok(false);
        };
        let Some(info) = array_type_info_from_row(&row) else {
            self.array_type_lookup_misses.insert(array_oid);
            return Ok(false);
        };

        self.register_array_type(info);
        Ok(true)
    }

    fn register_array_type(&mut self, info: ArrayTypeInfo) {
        register_array_type(&mut self.parsers, &mut self.serializers, info);
        self.array_type_lookup_misses.remove(&info.array_oid);
    }

    fn run_exec_command(&mut self, sql: &str) -> Result<()> {
        self.exec_internal(sql, None).map(|_| ())
    }

    fn handle_blob_input(&mut self, blob: Option<&Vec<u8>>) -> Result<()> {
        let path = self.dev_blob_path();
        if let Some(bytes) = blob {
            if let Some(parent) = path.parent() {
                fs::create_dir_all(parent).with_context(|| {
                    format!("failed to create blob directory {}", parent.display())
                })?;
            }
            fs::write(&path, bytes)
                .with_context(|| format!("write blob input to {}", path.display()))?;
            self.blob_input_provided = true;
        } else {
            self.blob_input_provided = false;
            let _ = fs::remove_file(&path);
        }
        Ok(())
    }

    fn dev_blob_path(&self) -> PathBuf {
        self.backend.paths().runtime_root().join("dev/blob")
    }

    fn cleanup_blob(&mut self) -> Result<()> {
        Ok(())
    }

    fn get_written_blob(&mut self) -> Result<Option<Vec<u8>>> {
        let path = self.dev_blob_path();

        if self.blob_input_provided {
            self.blob_input_provided = false;
            let _ = fs::remove_file(&path);
            return Ok(None);
        }

        match fs::read(&path) {
            Ok(data) => {
                self.blob_input_provided = false;
                let _ = fs::remove_file(&path);
                if data.is_empty() {
                    Ok(None)
                } else {
                    Ok(Some(data))
                }
            }
            Err(err) => {
                if err.kind() == io::ErrorKind::NotFound {
                    self.blob_input_provided = false;
                    Ok(None)
                } else {
                    Err(err).with_context(|| format!("read blob output from {}", path.display()))
                }
            }
        }
    }

    fn check_ready(&self) -> Result<()> {
        if self.closing {
            bail!("Pglite instance is closing");
        }
        if self.closed {
            bail!("Pglite instance is closed");
        }
        if !self.ready {
            bail!("Pglite instance is not ready");
        }
        Ok(())
    }
}

impl Drop for Pglite {
    fn drop(&mut self) {
        if !self.closed {
            let _ = self.close();
        }
    }
}

#[cfg(feature = "extensions")]
fn ensure_direct_pg_dump_options_match_session(
    startup_config: &StartupConfig,
    options: &PgDumpOptions,
) -> Result<()> {
    if options.database_ref() != startup_config.database {
        bail!(
            "direct pg_dump runs against the already-open embedded backend database '{}'; requested database '{}' would require a separate server connection",
            startup_config.database,
            options.database_ref()
        );
    }
    if options.username_ref() != startup_config.username {
        bail!(
            "direct pg_dump runs through the already-open embedded backend user '{}'; requested user '{}' would require a separate server connection",
            startup_config.username,
            options.username_ref()
        );
    }
    Ok(())
}

#[cfg(feature = "extensions")]
fn read_direct_pg_dump_socket(
    runtime: &Runtime,
    reader: &mut TcpSocketHalfRx,
    buffer: &mut [u8],
) -> Result<usize> {
    runtime
        .block_on(async {
            std::future::poll_fn(|cx| {
                let read = match reader.poll_fill_buf(cx) {
                    std::task::Poll::Ready(Ok(available)) => {
                        let read = available.len().min(buffer.len());
                        buffer[..read].copy_from_slice(&available[..read]);
                        read
                    }
                    std::task::Poll::Ready(Err(err)) => return std::task::Poll::Ready(Err(err)),
                    std::task::Poll::Pending => return std::task::Poll::Pending,
                };
                reader.consume(read);
                std::task::Poll::Ready(Ok(read))
            })
            .await
        })
        .context("read direct pg_dump virtual socket")
}

#[cfg(feature = "extensions")]
fn write_direct_pg_dump_socket(
    runtime: &Runtime,
    writer: &mut (impl AsyncWrite + Unpin),
    bytes: &[u8],
) -> Result<()> {
    runtime
        .block_on(writer.write_all(bytes))
        .context("write direct pg_dump virtual socket")
}

#[cfg(feature = "extensions")]
fn flush_direct_pg_dump_socket(
    runtime: &Runtime,
    writer: &mut (impl AsyncWrite + Unpin),
) -> Result<()> {
    runtime
        .block_on(writer.flush())
        .context("flush direct pg_dump virtual socket")
}

fn value_to_i32(value: Option<&Value>) -> Option<i32> {
    match value? {
        Value::Number(number) => number.as_i64().map(|value| value as i32),
        Value::String(string) => string.parse::<i32>().ok(),
        _ => None,
    }
}

fn value_to_char(value: Option<&Value>) -> Option<char> {
    match value? {
        Value::String(string) => string.chars().next(),
        _ => None,
    }
}

fn array_type_info_from_row(row: &Value) -> Option<ArrayTypeInfo> {
    let Value::Object(map) = row else {
        return None;
    };
    let element_oid = value_to_i32(map.get("oid"))?;
    let array_oid = value_to_i32(map.get("typarray"))?;
    if element_oid == 0 || array_oid == 0 {
        return None;
    }
    let delimiter = value_to_char(map.get("typdelim")).unwrap_or(',');
    Some(ArrayTypeInfo::new(element_oid, array_oid, delimiter))
}

/// Transaction handle used within [`Pglite::transaction`].
pub struct Transaction<'a> {
    client: &'a mut Pglite,
    closed: bool,
}

impl<'a> Transaction<'a> {
    fn new(client: &'a mut Pglite) -> Self {
        Self {
            client,
            closed: false,
        }
    }

    fn commit_internal(&mut self) -> Result<()> {
        self.ensure_open()?;
        self.client.exec_internal("COMMIT", None)?;
        self.closed = true;
        Ok(())
    }

    fn rollback_internal(&mut self) -> Result<()> {
        self.ensure_open()?;
        self.client.exec_internal("ROLLBACK", None)?;
        self.closed = true;
        Ok(())
    }

    fn ensure_open(&self) -> Result<()> {
        if self.closed {
            bail!("transaction is already closed");
        }
        Ok(())
    }

    pub fn query(
        &mut self,
        sql: &str,
        params: &[Value],
        options: Option<&QueryOptions>,
    ) -> Result<Results> {
        self.ensure_open()?;
        self.client.query_internal(sql, params, options)
    }

    pub fn exec(&mut self, sql: &str, options: Option<&QueryOptions>) -> Result<Vec<Results>> {
        self.ensure_open()?;
        self.client.exec_internal(sql, options)
    }

    pub fn refresh_array_types(&mut self) -> Result<()> {
        self.ensure_open()?;
        self.client.refresh_array_types_internal()
    }

    pub fn commit(&mut self) -> Result<()> {
        self.commit_internal()
    }

    pub fn rollback(&mut self) -> Result<()> {
        self.rollback_internal()
    }

    pub fn is_closed(&self) -> bool {
        self.closed
    }

    pub fn closed(&self) -> bool {
        self.closed
    }
}