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
// Copyright Materialize, Inc. and contributors. All rights reserved.
//
// Use of this software is governed by the Business Source License
// included in the LICENSE file.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0.
//! pgtest is a Postgres wire protocol tester using datadriven test files. It
//! can be used to send [specific
//! messages](https://www.postgresql.org/docs/current/protocol-message-formats.html)
//! to any Postgres-compatible server and record received messages.
//!
//! The following datadriven directives are supported. They support a
//! `conn=name` argument to specify a non-default connection.
//! - `send`: Sends input messages to the server. Arguments, if needed, are
//! specified using JSON. Refer to the associated types to see supported
//! arguments. Arguments can be omitted to use defaults.
//! - `until`: Waits until input messages have been received from the server.
//! Additional messages are accumulated and returned as well.
//!
//! The first time a `conn=name` argument is specified, `cluster=name` can also
//! be specified to set the sessions cluster on initial connection.
//!
//! During debugging, set the environment variable `PGTEST_VERBOSE=1` to see
//! messages sent and received.
//!
//! Supported `send` types:
//! - [`Query`](struct.Query.html)
//! - [`Parse`](struct.Parse.html)
//! - [`Describe`](struct.Describe.html)
//! - [`Bind`](struct.Bind.html)
//! - [`Execute`](struct.Execute.html)
//! - `Sync`
//!
//! Supported `until` arguments:
//! - `no_error_fields` causes `ErrorResponse` messages to have empty contents.
//! Useful when none of our fields match Postgres. For example `until
//! no_error_fields`.
//! - `err_field_typs` specifies the set of error message fields
//! ([reference](https://www.postgresql.org/docs/current/protocol-error-fields.html)).
//! The default is `CMS` (code, message, severity). For example: `until
//! err_field_typs=SC` would return the severity and code fields in any
//! ErrorResponse message.
//!
//! For example, to execute a simple prepared statement:
//! ```pgtest
//! send
//! Parse {"query": "SELECT $1::text, 1 + $2::int4"}
//! Bind {"values": ["blah", "4"]}
//! Execute
//! Sync
//! ----
//!
//! until
//! ReadyForQuery
//! ----
//! ParseComplete
//! BindComplete
//! DataRow {"fields":["blah","5"]}
//! CommandComplete {"tag":"SELECT 1"}
//! ReadyForQuery {"status":"I"}
//! ```
//!
//! # Usage while writing tests
//!
//! The expected way to use this while writing tests is to generate output from
//! a postgres server. Use the `pgtest-mz` directory if our output differs
//! incompatibly from postgres. Write your test, excluding any lines after the
//! `----` of the `until` directive. For example:
//! ```pgtest
//! send
//! Query {"query": "SELECT 1"}
//! ----
//!
//! until
//! ReadyForQuery
//! ----
//! ```
//! Then run the pgtest binary, enabling rewrites and pointing it at postgres:
//! ```shell
//! REWRITE=1 cargo run --bin mz-pgtest -- test/pgtest/test.pt --addr localhost:5432 --user postgres
//! ```
//! This will generate the expected output for the `until` directive. Now rerun
//! against a running Materialize server:
//! ```shell
//! cargo run --bin mz-pgtest -- test/pgtest/test.pt
//! ```
use std::collections::{BTreeMap, BTreeSet};
use std::fmt;
use std::io::{ErrorKind, Read, Write};
use std::net::TcpStream;
use std::time::{Duration, Instant};
use anyhow::{anyhow, bail};
use bytes::{BufMut, BytesMut};
use fallible_iterator::FallibleIterator;
use mz_ore::collections::CollectionExt;
use postgres_protocol::message::backend::Message;
use postgres_protocol::message::frontend;
use postgres_protocol::IsNull;
use serde::{Deserialize, Serialize};
struct PgConn {
stream: TcpStream,
recv_buf: BytesMut,
send_buf: BytesMut,
timeout: Duration,
verbose: bool,
}
impl PgConn {
fn new<'a>(
addr: &str,
user: &'a str,
timeout: Duration,
verbose: bool,
mut options: Vec<(&'a str, &'a str)>,
) -> anyhow::Result<Self> {
let mut conn = Self {
stream: TcpStream::connect(addr)?,
recv_buf: BytesMut::new(),
send_buf: BytesMut::new(),
timeout,
verbose,
};
conn.stream.set_read_timeout(Some(timeout))?;
options.insert(0, ("user", user));
options.insert(0, ("welcome_message", "off"));
conn.send(|buf| frontend::startup_message(options, buf).unwrap())?;
match conn.recv()?.1 {
Message::AuthenticationOk => {}
_ => bail!("expected AuthenticationOk"),
};
conn.until(vec!["ReadyForQuery"], vec!['C', 'S', 'M'], BTreeSet::new())?;
Ok(conn)
}
fn send<F: FnOnce(&mut BytesMut)>(&mut self, f: F) -> anyhow::Result<()> {
self.send_buf.clear();
f(&mut self.send_buf);
self.stream.write_all(&self.send_buf)?;
Ok(())
}
fn until(
&mut self,
until: Vec<&str>,
err_field_typs: Vec<char>,
ignore: BTreeSet<String>,
) -> anyhow::Result<Vec<String>> {
let mut msgs = Vec::with_capacity(until.len());
for expect in until {
loop {
let (ch, msg) = match self.recv() {
Ok((ch, msg)) => (ch, msg),
Err(err) => bail!("{}: waiting for {}, saw {:#?}", err, expect, msgs),
};
let (typ, args) = match msg {
Message::ReadyForQuery(body) => (
"ReadyForQuery",
serde_json::to_string(&ReadyForQuery {
status: char::from(body.status()).to_string(),
})?,
),
Message::RowDescription(body) => (
"RowDescription",
serde_json::to_string(&RowDescription {
fields: body
.fields()
.map(|f| {
Ok(Field {
name: f.name().to_string(),
})
})
.collect()
.unwrap(),
})?,
),
Message::DataRow(body) => {
let buf = body.buffer();
(
"DataRow",
serde_json::to_string(&DataRow {
fields: body
.ranges()
.map(|range| {
match range {
Some(range) => {
// Attempt to convert to a String. If not utf8, print as array of bytes instead.
Ok(String::from_utf8(
buf[range.start..range.end].to_vec(),
)
.unwrap_or_else(|_| {
format!(
"{:?}",
buf[range.start..range.end].to_vec()
)
}))
}
None => Ok("NULL".into()),
}
})
.collect()
.unwrap(),
})?,
)
}
Message::CommandComplete(body) => (
"CommandComplete",
serde_json::to_string(&CommandComplete {
tag: body.tag().unwrap().to_string(),
})?,
),
Message::ParseComplete => ("ParseComplete", "".to_string()),
Message::BindComplete => ("BindComplete", "".to_string()),
Message::PortalSuspended => ("PortalSuspended", "".to_string()),
Message::ErrorResponse(body) => (
"ErrorResponse",
serde_json::to_string(&ErrorResponse {
fields: body
.fields()
.filter_map(|f| {
let typ = char::from(f.type_());
if err_field_typs.contains(&typ) {
Ok(Some(ErrorField {
typ,
value: String::from_utf8_lossy(f.value_bytes())
.into_owned(),
}))
} else {
Ok(None)
}
})
.collect()
.unwrap(),
})?,
),
Message::NoticeResponse(body) => (
"NoticeResponse",
serde_json::to_string(&ErrorResponse {
fields: body
.fields()
.filter_map(|f| {
let typ = char::from(f.type_());
if err_field_typs.contains(&typ) {
Ok(Some(ErrorField {
typ,
value: String::from_utf8_lossy(f.value_bytes())
.into_owned(),
}))
} else {
Ok(None)
}
})
.collect()
.unwrap(),
})?,
),
Message::CopyOutResponse(body) => (
"CopyOut",
serde_json::to_string(&CopyOut {
format: format_name(body.format()),
column_formats: body
.column_formats()
.map(|format| Ok(format_name(format)))
.collect()
.unwrap(),
})?,
),
Message::CopyInResponse(body) => (
"CopyIn",
serde_json::to_string(&CopyOut {
format: format_name(body.format()),
column_formats: body
.column_formats()
.map(|format| Ok(format_name(format)))
.collect()
.unwrap(),
})?,
),
Message::CopyData(body) => (
"CopyData",
serde_json::to_string(
&std::str::from_utf8(body.data())
.map(|s| s.to_string())
.unwrap_or_else(|_| format!("{:?}", body.data())),
)?,
),
Message::CopyDone => ("CopyDone", "".to_string()),
Message::ParameterDescription(body) => (
"ParameterDescription",
serde_json::to_string(&ParameterDescription {
parameters: body.parameters().collect().unwrap(),
})?,
),
Message::ParameterStatus(_) => continue,
Message::NoData => ("NoData", "".to_string()),
Message::EmptyQueryResponse => ("EmptyQueryResponse", "".to_string()),
_ => ("UNKNOWN", format!("'{}'", ch)),
};
if self.verbose {
println!("RECV {}: {:?}", ch, typ);
}
if ignore.contains(typ) {
continue;
}
let mut s = typ.to_string();
if !args.is_empty() {
s.push(' ');
s.push_str(&args);
}
msgs.push(s);
if expect == typ {
break;
}
}
}
Ok(msgs)
}
/// Returns the PostgreSQL message format and the `Message`.
///
/// An error is returned if a new message is not received within the timeout.
pub fn recv(&mut self) -> anyhow::Result<(char, Message)> {
let mut buf = [0; 1024];
let until = Instant::now();
loop {
if until.elapsed() > self.timeout {
bail!("timeout after {:?} waiting for new message", self.timeout);
}
let mut ch: char = '0';
if self.recv_buf.len() > 0 {
ch = char::from(self.recv_buf[0]);
}
if let Some(msg) = Message::parse(&mut self.recv_buf)? {
return Ok((ch, msg));
};
// If there was no message, read more bytes.
let sz = match self.stream.read(&mut buf) {
Ok(n) => n,
// According to the `read` docs, this is a non-fatal retryable error.
// https://doc.rust-lang.org/std/io/trait.Read.html#errors
Err(e) if e.kind() == ErrorKind::Interrupted => continue,
Err(e) => return Err(anyhow!(e)),
};
self.recv_buf.extend_from_slice(&buf[..sz]);
}
}
}
const DEFAULT_CONN: &str = "";
pub struct PgTest {
addr: String,
user: String,
timeout: Duration,
conns: BTreeMap<String, PgConn>,
verbose: bool,
}
impl PgTest {
pub fn new(addr: String, user: String, timeout: Duration) -> anyhow::Result<Self> {
let verbose = std::env::var_os("PGTEST_VERBOSE").is_some();
let conn = PgConn::new(&addr, &user, timeout.clone(), verbose, vec![])?;
let mut conns = BTreeMap::new();
conns.insert(DEFAULT_CONN.to_string(), conn);
Ok(PgTest {
addr,
user,
timeout,
conns,
verbose,
})
}
// Returns the named connection. If this is the first time that connection is
// seen, sends options.
fn get_conn(
&mut self,
name: Option<String>,
options: Vec<(&str, &str)>,
) -> anyhow::Result<&mut PgConn> {
let name = name.unwrap_or_else(|| DEFAULT_CONN.to_string());
if !self.conns.contains_key(&name) {
let conn = PgConn::new(
&self.addr,
&self.user,
self.timeout.clone(),
self.verbose,
options,
)?;
self.conns.insert(name.clone(), conn);
}
Ok(self.conns.get_mut(&name).expect("must exist"))
}
pub fn send<F: Fn(&mut BytesMut)>(
&mut self,
conn: Option<String>,
options: Vec<(&str, &str)>,
f: F,
) -> anyhow::Result<()> {
let conn = self.get_conn(conn, options)?;
conn.send(f)
}
pub fn until(
&mut self,
conn: Option<String>,
options: Vec<(&str, &str)>,
until: Vec<&str>,
err_field_typs: Vec<char>,
ignore: BTreeSet<String>,
) -> anyhow::Result<Vec<String>> {
let conn = self.get_conn(conn, options)?;
conn.until(until, err_field_typs, ignore)
}
}
// Backend messages
#[derive(Serialize)]
pub struct ReadyForQuery {
pub status: String,
}
#[derive(Serialize)]
pub struct RowDescription {
pub fields: Vec<Field>,
}
#[derive(Serialize)]
pub struct Field {
pub name: String,
}
#[derive(Serialize)]
pub struct DataRow {
pub fields: Vec<String>,
}
#[derive(Serialize)]
pub struct CopyOut {
pub format: String,
pub column_formats: Vec<String>,
}
#[derive(Serialize)]
pub struct ParameterDescription {
parameters: Vec<u32>,
}
#[derive(Serialize)]
pub struct CommandComplete {
pub tag: String,
}
#[derive(Serialize)]
pub struct ErrorResponse {
pub fields: Vec<ErrorField>,
}
#[derive(Serialize)]
pub struct ErrorField {
pub typ: char,
pub value: String,
}
impl Drop for PgTest {
fn drop(&mut self) {
for conn in self.conns.values_mut() {
let _ = conn.send(frontend::terminate);
}
}
}
fn format_name<T>(format: T) -> String
where
T: Copy + TryInto<u16> + fmt::Display,
{
match format.try_into() {
Ok(0) => "text".to_string(),
Ok(1) => "binary".to_string(),
_ => format!("unknown: {}", format),
}
}
pub fn walk(addr: String, user: String, timeout: Duration, dir: &str) {
datadriven::walk(dir, |tf| run_test(tf, addr.clone(), user.clone(), timeout));
}
pub fn run_test(tf: &mut datadriven::TestFile, addr: String, user: String, timeout: Duration) {
let mut pgt = PgTest::new(addr, user, timeout).unwrap();
tf.run(|tc| -> String {
let lines = tc.input.lines();
let mut args = tc.args.clone();
let conn: Option<String> = args
.remove("conn")
.map(|args| Some(args.into_first()))
.unwrap_or(None);
let mut options: Vec<(&str, &str)> = Vec::new();
let cluster = args.remove("cluster");
if let Some(cluster) = &cluster {
let cluster = cluster.into_first();
options.push(("cluster", cluster.as_str()));
}
match tc.directive.as_str() {
"send" => {
for line in lines {
if pgt.verbose {
println!("SEND {}", line);
}
let mut line = line.splitn(2, ' ');
let typ = line.next().unwrap_or("");
let args = line.next().unwrap_or("{}");
pgt.send(conn.clone(), options.clone(), |buf| match typ {
"Query" => {
let v: Query = serde_json::from_str(args).unwrap();
frontend::query(&v.query, buf).unwrap();
}
"Parse" => {
let v: Parse = serde_json::from_str(args).unwrap();
frontend::parse(
&v.name.unwrap_or_else(|| "".into()),
&v.query,
vec![],
buf,
)
.unwrap();
}
"Sync" => frontend::sync(buf),
"Bind" => {
let v: Bind = serde_json::from_str(args).unwrap();
let values = v.values.unwrap_or_default();
if frontend::bind(
&v.portal.unwrap_or_else(|| "".into()),
&v.statement.unwrap_or_else(|| "".into()),
vec![], // formats
values, // values
|t, buf| {
buf.put_slice(t.as_bytes());
Ok(IsNull::No)
}, // serializer
v.result_formats.unwrap_or_default(),
buf,
)
.is_err()
{
panic!("bind error");
}
}
"Describe" => {
let v: Describe = serde_json::from_str(args).unwrap();
frontend::describe(
v.variant.unwrap_or_else(|| "S".into()).as_bytes()[0],
&v.name.unwrap_or_else(|| "".into()),
buf,
)
.unwrap();
}
"Execute" => {
let v: Execute = serde_json::from_str(args).unwrap();
frontend::execute(
&v.portal.unwrap_or_else(|| "".into()),
v.max_rows.unwrap_or(0),
buf,
)
.unwrap();
}
"CopyData" => {
let v: String = serde_json::from_str(args).unwrap();
frontend::CopyData::new(v.as_bytes()).unwrap().write(buf);
}
"CopyDone" => {
frontend::copy_done(buf);
}
"CopyFail" => {
let v: String = serde_json::from_str(args).unwrap();
frontend::copy_fail(&v, buf).unwrap();
}
_ => panic!("unknown message type {}", typ),
})
.unwrap();
}
"".to_string()
}
"until" => {
// Our error field values don't always match postgres. Default to reporting
// the error code (C) and message (M), but allow the user to specify which ones
// they want.
let err_field_typs = if let Some(_) = args.remove("no_error_fields") {
vec![]
} else {
match args.remove("err_field_typs") {
Some(typs) => typs.join("").chars().collect(),
None => vec!['C', 'S', 'M'],
}
};
let mut ignore = BTreeSet::new();
if let Some(values) = args.remove("ignore") {
for v in values {
ignore.insert(v);
}
}
if !args.is_empty() {
panic!("extra until arguments: {:?}", args);
}
format!(
"{}\n",
pgt.until(conn, options, lines.collect(), err_field_typs, ignore)
.unwrap()
.join("\n")
)
}
_ => panic!("unknown directive {}", tc.input),
}
})
}
// Frontend messages
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Query {
pub query: String,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Parse {
pub name: Option<String>,
pub query: String,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Bind {
pub portal: Option<String>,
pub statement: Option<String>,
pub values: Option<Vec<String>>,
pub result_formats: Option<Vec<i16>>,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Execute {
pub portal: Option<String>,
pub max_rows: Option<i32>,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Describe {
pub variant: Option<String>,
pub name: Option<String>,
}