diff --git a/fuzz/fuzz_seeds/postgres_create_table_like_mixed_elements.sql b/fuzz/fuzz_seeds/postgres_create_table_like_mixed_elements.sql new file mode 100644 index 0000000000..6a56dfd09d --- /dev/null +++ b/fuzz/fuzz_seeds/postgres_create_table_like_mixed_elements.sql @@ -0,0 +1 @@ +CREATE TABLE t (b INT, LIKE a INCLUDING DEFAULTS, c INT, LIKE d) diff --git a/src/ast/ddl.rs b/src/ast/ddl.rs index dfdd25ecf8..1aeb70fd66 100644 --- a/src/ast/ddl.rs +++ b/src/ast/ddl.rs @@ -42,18 +42,18 @@ use crate::ast::{ UniqueConstraint, }, ArgMode, AttachedToken, BeginEndStatements, CommentDef, ConditionalStatements, - CreateFunctionBody, CreateFunctionUsing, CreateServerOption, CreateTableLikeKind, - CreateTableOptions, CreateViewParams, DataType, Expr, FileFormat, FunctionBehavior, - FunctionCalledOnNull, FunctionDefinitionSetParam, FunctionDesc, FunctionDeterminismSpecifier, - FunctionParallel, FunctionSecurity, HiveDistributionStyle, HiveFormat, HiveIOFormat, - HiveRowFormat, HiveSetLocation, Ident, InitializeKind, MySQLColumnPosition, ObjectName, - OnCommit, OneOrManyWithParens, OperateFunctionArg, OrderByExpr, ProjectionSelect, Query, - RefreshModeKind, ResetConfig, RowAccessPolicy, SequenceOptions, Spanned, SqlOption, Statement, - StorageLifecyclePolicy, StorageSerializationPolicy, TableVersion, Tag, TriggerEvent, - TriggerExecBody, TriggerObject, TriggerPeriod, TriggerReferencing, Value, ValueWithSpan, - WrappedCollection, + CreateFunctionBody, CreateFunctionUsing, CreateServerOption, CreateTableLikeElement, + CreateTableLikeKind, CreateTableOptions, CreateViewParams, DataType, Expr, FileFormat, + FunctionBehavior, FunctionCalledOnNull, FunctionDefinitionSetParam, FunctionDesc, + FunctionDeterminismSpecifier, FunctionParallel, FunctionSecurity, HiveDistributionStyle, + HiveFormat, HiveIOFormat, HiveRowFormat, HiveSetLocation, Ident, InitializeKind, + MySQLColumnPosition, ObjectName, OnCommit, OneOrManyWithParens, OperateFunctionArg, + OrderByExpr, ProjectionSelect, Query, RefreshModeKind, ResetConfig, RowAccessPolicy, + SequenceOptions, Spanned, SqlOption, Statement, StorageLifecyclePolicy, + StorageSerializationPolicy, TableVersion, Tag, TriggerEvent, TriggerExecBody, TriggerObject, + TriggerPeriod, TriggerReferencing, Value, ValueWithSpan, WrappedCollection, }; -use crate::display_utils::{DisplayCommaSeparated, Indent, NewLine, SpaceOrNewline}; +use crate::display_utils::{Indent, NewLine, SpaceOrNewline}; use crate::keywords::Keyword; use crate::tokenizer::{Span, Token}; @@ -3453,15 +3453,19 @@ impl fmt::Display for CreateTable { if let Some(on_cluster) = &self.on_cluster { write!(f, " ON CLUSTER {on_cluster}")?; } - if !self.columns.is_empty() || !self.constraints.is_empty() { + let like_elements: &[CreateTableLikeElement] = match &self.like { + Some(CreateTableLikeKind::Parenthesized(like_elements)) => like_elements, + _ => &[], + }; + if !self.columns.is_empty() || !self.constraints.is_empty() || !like_elements.is_empty() { f.write_str(" (")?; NewLine.fmt(f)?; - Indent(DisplayCommaSeparated(&self.columns)).fmt(f)?; - if !self.columns.is_empty() && !self.constraints.is_empty() { - f.write_str(",")?; - SpaceOrNewline.fmt(f)?; - } - Indent(DisplayCommaSeparated(&self.constraints)).fmt(f)?; + Indent(TableElements { + columns: &self.columns, + like_elements, + constraints: &self.constraints, + }) + .fmt(f)?; NewLine.fmt(f)?; f.write_str(")")?; } else if self.query.is_none() @@ -3471,8 +3475,6 @@ impl fmt::Display for CreateTable { { // PostgreSQL allows `CREATE TABLE t ();`, but requires empty parens f.write_str(" ()")?; - } else if let Some(CreateTableLikeKind::Parenthesized(like_in_columns_list)) = &self.like { - write!(f, " ({like_in_columns_list})")?; } if let Some(for_values) = &self.for_values { write!(f, " {for_values}")?; @@ -3744,6 +3746,43 @@ impl fmt::Display for CreateTable { } } +/// The column list of `CREATE TABLE`, with each `LIKE` element after the columns written before it. +struct TableElements<'a> { + columns: &'a [ColumnDef], + like_elements: &'a [CreateTableLikeElement], + constraints: &'a [TableConstraint], +} + +impl fmt::Display for TableElements<'_> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let mut first = true; + let mut write_element = |f: &mut fmt::Formatter, element: &dyn fmt::Display| { + if !first { + f.write_char(',')?; + SpaceOrNewline.fmt(f)?; + } + first = false; + element.fmt(f) + }; + let mut like_elements = self.like_elements.iter().peekable(); + for (index, column) in self.columns.iter().enumerate() { + while let Some(like_element) = + like_elements.next_if(|like| like.columns_before <= index) + { + write_element(f, &like_element.like)?; + } + write_element(f, column)?; + } + for like_element in like_elements { + write_element(f, &like_element.like)?; + } + for constraint in self.constraints { + write_element(f, constraint)?; + } + Ok(()) + } +} + /// `WITH DATA` clause on `CREATE TABLE ... AS` statement. /// /// [Teradata](https://docs.teradata.com/r/Enterprise_IntelliFlex_VMware/SQL-Data-Definition-Language-Syntax-and-Examples/Table-Statements/CREATE-TABLE-and-CREATE-TABLE-AS/Syntax-Elements/AS_clause/WITH-Clause-Phrase) diff --git a/src/ast/mod.rs b/src/ast/mod.rs index 3325aa6fc4..387ad3d08f 100644 --- a/src/ast/mod.rs +++ b/src/ast/mod.rs @@ -12311,10 +12311,11 @@ impl Display for AlterUserPassword { #[cfg_attr(feature = "visitor", derive(Visit, VisitMut))] pub enum CreateTableLikeKind { /// '''sql - /// CREATE TABLE new (LIKE old ...) + /// CREATE TABLE new (LIKE old ..., column ...) /// ''' + /// [PostgreSQL](https://www.postgresql.org/docs/current/sql-createtable.html) /// [Redshift](https://docs.aws.amazon.com/redshift/latest/dg/r_CREATE_TABLE_NEW.html) - Parenthesized(CreateTableLike), + Parenthesized(Vec), /// '''sql /// CREATE TABLE new LIKE old ... /// ''' @@ -12323,6 +12324,17 @@ pub enum CreateTableLikeKind { Plain(CreateTableLike), } +/// A `LIKE` element of a `CREATE TABLE` column list. +#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)] +#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] +#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))] +pub struct CreateTableLikeElement { + /// The copied table and its options. + pub like: CreateTableLike, + /// The number of columns written before this element, which sets where the copied columns go. + pub columns_before: usize, +} + /// An option of a `CREATE TABLE ... (LIKE ...)` clause. A later option overrides an earlier one. /// /// [PostgreSQL](https://www.postgresql.org/docs/current/sql-createtable.html) diff --git a/src/ast/visitor.rs b/src/ast/visitor.rs index c78ff2bfb9..3db43d9a6e 100644 --- a/src/ast/visitor.rs +++ b/src/ast/visitor.rs @@ -128,7 +128,7 @@ macro_rules! visit_noop { }; } -visit_noop!(u8, u16, u32, u64, i8, i16, i32, i64, char, bool, String); +visit_noop!(u8, u16, u32, u64, usize, i8, i16, i32, i64, char, bool, String); #[cfg(feature = "bigdecimal")] visit_noop!(bigdecimal::BigDecimal); diff --git a/src/parser/mod.rs b/src/parser/mod.rs index b8e0004d57..7ed970f431 100644 --- a/src/parser/mod.rs +++ b/src/parser/mod.rs @@ -9516,10 +9516,25 @@ impl<'a> Parser<'a> { }; // parse optional column list (schema) + let mut like_elements = vec![]; let (columns, constraints) = if partition_of.is_some() { self.parse_partition_of_columns()? } else { - self.parse_columns()? + let accepts_like = self.dialect.supports_create_table_like_parenthesized(); + self.parse_table_elements( + Parser::parse_column_def, + accepts_like.then_some(&mut like_elements), + )? + }; + let like = if like_elements.is_empty() { + like + } else if like.is_some() { + return parser_err!( + "CREATE TABLE cannot take LIKE both before and inside the column list", + like_elements[0].like.name.span().start + ); + } else { + Some(CreateTableLikeKind::Parenthesized(like_elements)) }; let comment_after_column_def = if dialect_of!(self is HiveDialect) && self.parse_keyword(Keyword::COMMENT) { @@ -9759,69 +9774,60 @@ impl<'a> Parser<'a> { &mut self, allow_unquoted_hyphen: bool, ) -> Result, ParserError> { - let like = if self.dialect.supports_create_table_like_parenthesized() - && self.consume_token(&Token::LParen) - { - if self.parse_keyword(Keyword::LIKE) { - let name = self.parse_object_name(allow_unquoted_hyphen)?; - let mut options = Vec::new(); - while let Some(keyword) = - self.parse_one_of_keywords(&[Keyword::INCLUDING, Keyword::EXCLUDING]) - { - let property = match self.expect_one_of_keywords(&[ - Keyword::ALL, - Keyword::COMMENTS, - Keyword::COMPRESSION, - Keyword::CONSTRAINTS, - Keyword::DEFAULTS, - Keyword::GENERATED, - Keyword::IDENTITY, - Keyword::INDEXES, - Keyword::STATISTICS, - Keyword::STORAGE, - ])? { - Keyword::ALL => CreateTableLikeProperty::All, - Keyword::COMMENTS => CreateTableLikeProperty::Comments, - Keyword::COMPRESSION => CreateTableLikeProperty::Compression, - Keyword::CONSTRAINTS => CreateTableLikeProperty::Constraints, - Keyword::DEFAULTS => CreateTableLikeProperty::Defaults, - Keyword::GENERATED => CreateTableLikeProperty::Generated, - Keyword::IDENTITY => CreateTableLikeProperty::Identity, - Keyword::INDEXES => CreateTableLikeProperty::Indexes, - Keyword::STATISTICS => CreateTableLikeProperty::Statistics, - Keyword::STORAGE => CreateTableLikeProperty::Storage, - other => { - return Err(ParserError::ParserError(format!( - "Internal parser error: unexpected LIKE option {other:?}" - ))) - } - }; - options.push(if keyword == Keyword::INCLUDING { - CreateTableLikeOption::Including(property) - } else { - CreateTableLikeOption::Excluding(property) - }); - } - self.expect_token(&Token::RParen)?; - Some(CreateTableLikeKind::Parenthesized(CreateTableLike { - name, - options, - })) - } else { - // Rollback the '(' it's probably the columns list - self.prev_token(); - None - } - } else if self.parse_keyword(Keyword::LIKE) || self.parse_keyword(Keyword::ILIKE) { + if self.parse_keyword(Keyword::LIKE) || self.parse_keyword(Keyword::ILIKE) { let name = self.parse_object_name(allow_unquoted_hyphen)?; - Some(CreateTableLikeKind::Plain(CreateTableLike { + Ok(Some(CreateTableLikeKind::Plain(CreateTableLike { name, options: vec![], - })) + }))) } else { - None - }; - Ok(like) + Ok(None) + } + } + + /// Parse the `INCLUDING` and `EXCLUDING` options of a `LIKE` element in a `CREATE TABLE` column list. + fn parse_create_table_like_options( + &mut self, + ) -> Result, ParserError> { + let mut options = Vec::new(); + while let Some(keyword) = + self.parse_one_of_keywords(&[Keyword::INCLUDING, Keyword::EXCLUDING]) + { + let property = match self.expect_one_of_keywords(&[ + Keyword::ALL, + Keyword::COMMENTS, + Keyword::COMPRESSION, + Keyword::CONSTRAINTS, + Keyword::DEFAULTS, + Keyword::GENERATED, + Keyword::IDENTITY, + Keyword::INDEXES, + Keyword::STATISTICS, + Keyword::STORAGE, + ])? { + Keyword::ALL => CreateTableLikeProperty::All, + Keyword::COMMENTS => CreateTableLikeProperty::Comments, + Keyword::COMPRESSION => CreateTableLikeProperty::Compression, + Keyword::CONSTRAINTS => CreateTableLikeProperty::Constraints, + Keyword::DEFAULTS => CreateTableLikeProperty::Defaults, + Keyword::GENERATED => CreateTableLikeProperty::Generated, + Keyword::IDENTITY => CreateTableLikeProperty::Identity, + Keyword::INDEXES => CreateTableLikeProperty::Indexes, + Keyword::STATISTICS => CreateTableLikeProperty::Statistics, + Keyword::STORAGE => CreateTableLikeProperty::Storage, + other => { + return Err(ParserError::ParserError(format!( + "Internal parser error: unexpected LIKE option {other:?}" + ))) + } + }; + options.push(if keyword == Keyword::INCLUDING { + CreateTableLikeOption::Including(property) + } else { + CreateTableLikeOption::Excluding(property) + }); + } + Ok(options) } pub(crate) fn parse_create_table_on_commit(&mut self) -> Result { @@ -10237,7 +10243,7 @@ impl<'a> Parser<'a> { /// Parse columns and constraints. pub fn parse_columns(&mut self) -> Result<(Vec, Vec), ParserError> { - self.parse_table_elements(Parser::parse_column_def) + self.parse_table_elements(Parser::parse_column_def, None) } /// Parse the columns and constraints of a `PARTITION OF` table, whose column entries @@ -10247,20 +10253,26 @@ impl<'a> Parser<'a> { fn parse_partition_of_columns( &mut self, ) -> Result<(Vec, Vec), ParserError> { - self.parse_table_elements(|parser| { - let name = parser.parse_identifier()?; - let _ = parser.parse_keywords(&[Keyword::WITH, Keyword::OPTIONS]); // [ WITH OPTIONS ] - Ok(ColumnDef { - name, - data_type: DataType::Unspecified, - options: parser.parse_column_option_defs()?, - }) - }) + self.parse_table_elements( + |parser| { + let name = parser.parse_identifier()?; + let _ = parser.parse_keywords(&[Keyword::WITH, Keyword::OPTIONS]); // [ WITH OPTIONS ] + Ok(ColumnDef { + name, + data_type: DataType::Unspecified, + options: parser.parse_column_option_defs()?, + }) + }, + None, + ) } + /// Parse a parenthesized list of columns and constraints, and of `LIKE` elements when + /// `like_elements` is given. fn parse_table_elements( &mut self, mut parse_column: impl FnMut(&mut Self) -> Result, + mut like_elements: Option<&mut Vec>, ) -> Result<(Vec, Vec), ParserError> { let mut columns = vec![]; let mut constraints = vec![]; @@ -10269,7 +10281,18 @@ impl<'a> Parser<'a> { } loop { - if let Some(constraint) = self.parse_optional_table_constraint()? { + if let Some(like_elements) = like_elements + .as_deref_mut() + .filter(|_| self.parse_keyword(Keyword::LIKE)) + { + like_elements.push(CreateTableLikeElement { + like: CreateTableLike { + name: self.parse_object_name(false)?, + options: self.parse_create_table_like_options()?, + }, + columns_before: columns.len(), + }); + } else if let Some(constraint) = self.parse_optional_table_constraint()? { constraints.push(constraint); } else if let Token::Word(_) = &self.peek_token_ref().token { columns.push(parse_column(self)?); diff --git a/tests/sqlparser_common.rs b/tests/sqlparser_common.rs index 2a3029a362..7de9d4e7c6 100644 --- a/tests/sqlparser_common.rs +++ b/tests/sqlparser_common.rs @@ -20299,10 +20299,15 @@ fn parse_create_table_like() { ); assert_eq!( stmt.like, - Some(CreateTableLikeKind::Parenthesized(CreateTableLike { - name: ObjectName::from(vec![Ident::new("old".to_string())]), - options: vec![], - })) + Some(CreateTableLikeKind::Parenthesized(vec![ + CreateTableLikeElement { + like: CreateTableLike { + name: ObjectName::from(vec![Ident::new("old".to_string())]), + options: vec![], + }, + columns_before: 0, + } + ])) ) } _ => unreachable!(), @@ -20316,12 +20321,17 @@ fn parse_create_table_like() { ); assert_eq!( stmt.like, - Some(CreateTableLikeKind::Parenthesized(CreateTableLike { - name: ObjectName::from(vec![Ident::new("old".to_string())]), - options: vec![CreateTableLikeOption::Including( - CreateTableLikeProperty::Defaults - )], - })) + Some(CreateTableLikeKind::Parenthesized(vec![ + CreateTableLikeElement { + like: CreateTableLike { + name: ObjectName::from(vec![Ident::new("old".to_string())]), + options: vec![CreateTableLikeOption::Including( + CreateTableLikeProperty::Defaults + )], + }, + columns_before: 0, + } + ])) ) } _ => unreachable!(), @@ -20335,12 +20345,17 @@ fn parse_create_table_like() { ); assert_eq!( stmt.like, - Some(CreateTableLikeKind::Parenthesized(CreateTableLike { - name: ObjectName::from(vec![Ident::new("old".to_string())]), - options: vec![CreateTableLikeOption::Excluding( - CreateTableLikeProperty::Defaults - )], - })) + Some(CreateTableLikeKind::Parenthesized(vec![ + CreateTableLikeElement { + like: CreateTableLike { + name: ObjectName::from(vec![Ident::new("old".to_string())]), + options: vec![CreateTableLikeOption::Excluding( + CreateTableLikeProperty::Defaults + )], + }, + columns_before: 0, + } + ])) ) } _ => unreachable!(), @@ -23642,3 +23657,95 @@ fn parse_only_table_name() { dialects.verified_stmt(sql); } } + +#[test] +fn parse_create_table_like_among_columns() { + let dialects = all_dialects_where(|dialect| dialect.supports_create_table_like_parenthesized()); + let like = |name: &str, options, columns_before| CreateTableLikeElement { + like: CreateTableLike { + name: ObjectName::from(vec![Ident::new(name)]), + options, + }, + columns_before, + }; + let column_names = |create_table: &CreateTable| -> Vec { + create_table + .columns + .iter() + .map(|column| column.name.to_string()) + .collect() + }; + + match dialects.verified_stmt("CREATE TABLE t (LIKE a, b INT)") { + Statement::CreateTable(create_table) => { + assert_eq!( + create_table.like, + Some(CreateTableLikeKind::Parenthesized(vec![like( + "a", + vec![], + 0 + )])) + ); + assert_eq!(column_names(&create_table), ["b"]); + } + _ => unreachable!(), + } + match dialects.verified_stmt("CREATE TABLE t (b INT, LIKE a)") { + Statement::CreateTable(create_table) => { + assert_eq!( + create_table.like, + Some(CreateTableLikeKind::Parenthesized(vec![like( + "a", + vec![], + 1 + )])) + ); + assert_eq!(column_names(&create_table), ["b"]); + } + _ => unreachable!(), + } + match dialects.verified_stmt( + "CREATE TABLE t (b INT, LIKE a INCLUDING DEFAULTS, c INT, LIKE d, PRIMARY KEY (b))", + ) { + Statement::CreateTable(create_table) => { + assert_eq!( + create_table.like, + Some(CreateTableLikeKind::Parenthesized(vec![ + like( + "a", + vec![CreateTableLikeOption::Including( + CreateTableLikeProperty::Defaults + )], + 1 + ), + like("d", vec![], 2), + ])) + ); + assert_eq!(column_names(&create_table), ["b", "c"]); + assert_eq!(create_table.constraints.len(), 1); + } + _ => unreachable!(), + } + match dialects.verified_stmt(r#"CREATE TABLE t ("LIKE" INT)"#) { + Statement::CreateTable(create_table) => { + assert_eq!(create_table.like, None); + assert_eq!(column_names(&create_table), [r#""LIKE""#]); + } + _ => unreachable!(), + } + + assert_eq!( + dialects + .parse_sql_statements("CREATE TABLE t (b INT, LIKE)") + .unwrap_err(), + ParserError::ParserError("Expected: identifier, found: )".to_string()) + ); + assert_eq!( + dialects + .parse_sql_statements("CREATE TABLE t LIKE a (LIKE b)") + .unwrap_err(), + ParserError::ParserError( + "CREATE TABLE cannot take LIKE both before and inside the column list".to_string() + ) + ); +} diff --git a/tests/sqlparser_postgres.rs b/tests/sqlparser_postgres.rs index 1d9300c423..cd76770c26 100644 --- a/tests/sqlparser_postgres.rs +++ b/tests/sqlparser_postgres.rs @@ -692,12 +692,17 @@ fn parse_create_table_like_with_defaults() { ); assert_eq!( stmt.like, - Some(CreateTableLikeKind::Parenthesized(CreateTableLike { - name: ObjectName::from(vec![Ident::new("old".to_string())]), - options: vec![CreateTableLikeOption::Including( - CreateTableLikeProperty::Defaults - )], - })) + Some(CreateTableLikeKind::Parenthesized(vec![ + CreateTableLikeElement { + like: CreateTableLike { + name: ObjectName::from(vec![Ident::new("old".to_string())]), + options: vec![CreateTableLikeOption::Including( + CreateTableLikeProperty::Defaults + )], + }, + columns_before: 0, + } + ])) ) } _ => unreachable!(), @@ -712,12 +717,17 @@ fn parse_create_table_like_with_defaults() { ); assert_eq!( stmt.like, - Some(CreateTableLikeKind::Parenthesized(CreateTableLike { - name: ObjectName::from(vec![Ident::new("old".to_string())]), - options: vec![CreateTableLikeOption::Excluding( - CreateTableLikeProperty::Defaults - )], - })) + Some(CreateTableLikeKind::Parenthesized(vec![ + CreateTableLikeElement { + like: CreateTableLike { + name: ObjectName::from(vec![Ident::new("old".to_string())]), + options: vec![CreateTableLikeOption::Excluding( + CreateTableLikeProperty::Defaults + )], + }, + columns_before: 0, + } + ])) ) } _ => unreachable!(), @@ -14386,14 +14396,19 @@ fn parse_create_table_like_options() { ) { Statement::CreateTable(stmt) => assert_eq!( stmt.like, - Some(CreateTableLikeKind::Parenthesized(CreateTableLike { - name: ObjectName::from(vec![Ident::new("old")]), - options: vec![ - CreateTableLikeOption::Including(CreateTableLikeProperty::All), - CreateTableLikeOption::Excluding(CreateTableLikeProperty::Indexes), - CreateTableLikeOption::Including(CreateTableLikeProperty::Indexes), - ], - })) + Some(CreateTableLikeKind::Parenthesized(vec![ + CreateTableLikeElement { + like: CreateTableLike { + name: ObjectName::from(vec![Ident::new("old")]), + options: vec![ + CreateTableLikeOption::Including(CreateTableLikeProperty::All), + CreateTableLikeOption::Excluding(CreateTableLikeProperty::Indexes), + CreateTableLikeOption::Including(CreateTableLikeProperty::Indexes), + ], + }, + columns_before: 0, + } + ])) ), _ => unreachable!(), } @@ -14408,7 +14423,9 @@ fn parse_create_table_like_options() { assert_eq!( pg().parse_sql_statements("CREATE TABLE new (LIKE old COMMENTS)") .unwrap_err(), - ParserError::ParserError("Expected: ), found: COMMENTS".to_string()) + ParserError::ParserError( + "Expected: ',' or ')' after column definition, found: COMMENTS".to_string() + ) ); assert_eq!( pg().parse_sql_statements("CREATE TABLE new (LIKE)") @@ -14439,3 +14456,38 @@ fn display_create_table_like_propagates_write_errors() { assert_eq!(write!(writer, "{statement}"), Err(fmt::Error), "{rejected}"); } } + +#[test] +fn display_create_table_like_among_columns_propagates_write_errors() { + use core::fmt::{self, Write}; + + /// Fails only the write numbered `failing`, so a swallowed error lets formatting succeed. + struct FailingWriter { + failing: usize, + writes: usize, + } + + impl Write for FailingWriter { + fn write_str(&mut self, _: &str) -> fmt::Result { + let index = self.writes; + self.writes += 1; + if index == self.failing { + Err(fmt::Error) + } else { + Ok(()) + } + } + } + + let statement = pg() + .verified_stmt("CREATE TABLE t (LIKE a, b INT, LIKE c, d INT, LIKE e, PRIMARY KEY (b))"); + let mut counter = FailingWriter { + failing: usize::MAX, + writes: 0, + }; + write!(counter, "{statement}").unwrap(); + for failing in 0..counter.writes { + let mut writer = FailingWriter { failing, writes: 0 }; + assert_eq!(write!(writer, "{statement}"), Err(fmt::Error), "{failing}"); + } +}