Formats this SQL fragment by replacing each `{}` with the next SQL argument. Use `{{` and `}}` to escape literal braces.
(self, args: impl IntoIterator<Item = Sql>)
| 184 | /// |
| 185 | /// Use `{{` and `}}` to escape literal braces. |
| 186 | pub fn format(self, args: impl IntoIterator<Item = Sql>) -> Result<Self, SqlFormatError> { |
| 187 | let mut args = args.into_iter(); |
| 188 | let mut out = String::with_capacity(self.0.len()); |
| 189 | let mut chars = self.0.chars().peekable(); |
| 190 | |
| 191 | while let Some(ch) = chars.next() { |
| 192 | match ch { |
| 193 | '{' => match chars.peek() { |
| 194 | Some('{') => { |
| 195 | chars.next(); |
| 196 | out.push('{'); |
| 197 | } |
| 198 | Some('}') => { |
| 199 | chars.next(); |
| 200 | let arg = args.next().ok_or(SqlFormatError::MissingArgument)?; |
| 201 | out.push_str(arg.as_str()); |
| 202 | } |
| 203 | _ => return Err(SqlFormatError::InvalidOpenBrace), |
| 204 | }, |
| 205 | '}' => match chars.peek() { |
| 206 | Some('}') => { |
| 207 | chars.next(); |
| 208 | out.push('}'); |
| 209 | } |
| 210 | _ => return Err(SqlFormatError::InvalidCloseBrace), |
| 211 | }, |
| 212 | _ => out.push(ch), |
| 213 | } |
| 214 | } |
| 215 | |
| 216 | if args.next().is_some() { |
| 217 | return Err(SqlFormatError::ExtraArgument); |
| 218 | } |
| 219 | Ok(Sql(Cow::Owned(out))) |
| 220 | } |
| 221 | |
| 222 | /// Like [`Sql::format`], but panics on invalid input instead of returning |
| 223 | /// an error. |