|
11 | 11 |
|
12 | 12 | use itertools::Itertools; |
13 | 13 | use smallvec::SmallVec; |
| 14 | +use std::collections::BTreeMap; |
| 15 | +use std::fmt; |
14 | 16 | use std::sync::Arc; |
15 | 17 |
|
16 | 18 | use crate::cdc::{Lsn, RowFilterOption}; |
| 19 | +use crate::desc::{SqlServerColumnRaw, SqlServerTableRaw}; |
17 | 20 | use crate::{Client, SqlServerError}; |
18 | 21 |
|
19 | 22 | /// Returns the minimum log sequence number for the specified `capture_instance`. |
@@ -159,3 +162,151 @@ WHERE c.capture_instance IN ({param_indexes});" |
159 | 162 |
|
160 | 163 | Ok(tables) |
161 | 164 | } |
| 165 | + |
| 166 | +/// Ensure change data capture (CDC) is enabled for the database the provided |
| 167 | +/// `client` is currently connected to. |
| 168 | +/// |
| 169 | +/// See: <https://learn.microsoft.com/en-us/sql/relational-databases/track-changes/enable-and-disable-change-data-capture-sql-server?view=sql-server-ver16> |
| 170 | +pub async fn ensure_database_cdc_enabled(client: &mut Client) -> Result<(), SqlServerError> { |
| 171 | + static DATABASE_CDC_ENABLED_QUERY: &str = |
| 172 | + "SELECT is_cdc_enabled FROM sys.databases WHERE database_id = DB_ID();"; |
| 173 | + let result = client.simple_query(DATABASE_CDC_ENABLED_QUERY).await?; |
| 174 | + |
| 175 | + check_system_result(&result, "database CDC".to_string(), true)?; |
| 176 | + Ok(()) |
| 177 | +} |
| 178 | + |
| 179 | +/// Ensure change data capture (CDC) is enabled for the specified table. |
| 180 | +/// |
| 181 | +/// See: <https://learn.microsoft.com/en-us/sql/relational-databases/track-changes/enable-and-disable-change-data-capture-sql-server?view=sql-server-ver16#enable-for-a-table> |
| 182 | +pub async fn ensure_table_cdc_enabled( |
| 183 | + client: &mut Client, |
| 184 | + schema: &str, |
| 185 | + table: &str, |
| 186 | +) -> Result<(), SqlServerError> { |
| 187 | + static TABLE_CDC_ENABLED_QUERY: &str = " |
| 188 | +SELECT is_tracked_by_cdc FROM sys.tables tables |
| 189 | +JOIN sys.schemas schemas |
| 190 | +ON tables.schema_id = schemas.schema_id |
| 191 | +WHERE schemas.name = @P1 AND tables.name = @P2; |
| 192 | +"; |
| 193 | + let result = client |
| 194 | + .query(TABLE_CDC_ENABLED_QUERY, &[&schema, &table]) |
| 195 | + .await?; |
| 196 | + |
| 197 | + check_system_result(&result, "table CDC".to_string(), true)?; |
| 198 | + Ok(()) |
| 199 | +} |
| 200 | + |
| 201 | +/// Ensure the `SNAPSHOT` transaction isolation level is enabled for the |
| 202 | +/// database the provided `client` is currently connected to. |
| 203 | +/// |
| 204 | +/// See: <https://learn.microsoft.com/en-us/sql/t-sql/statements/set-transaction-isolation-level-transact-sql?view=sql-server-ver16> |
| 205 | +pub async fn ensure_snapshot_isolation_enabled(client: &mut Client) -> Result<(), SqlServerError> { |
| 206 | + static SNAPSHOT_ISOLATION_QUERY: &str = |
| 207 | + "SELECT snapshot_isolation_state FROM sys.databases WHERE database_id = DB_ID();"; |
| 208 | + let result = client.simple_query(SNAPSHOT_ISOLATION_QUERY).await?; |
| 209 | + |
| 210 | + check_system_result(&result, "snapshot isolation".to_string(), 1u8)?; |
| 211 | + Ok(()) |
| 212 | +} |
| 213 | + |
| 214 | +pub async fn get_tables(client: &mut Client) -> Result<Vec<SqlServerTableRaw>, SqlServerError> { |
| 215 | + static GET_TABLES_QUERY: &str = " |
| 216 | +SELECT |
| 217 | + s.name as schema_name, |
| 218 | + t.name as table_name, |
| 219 | + ch.capture_instance as capture_instance, |
| 220 | + c.name as col_name, |
| 221 | + ty.name as col_type, |
| 222 | + c.is_nullable as col_nullable, |
| 223 | + c.max_length as col_max_length, |
| 224 | + c.precision as col_precision, |
| 225 | + c.scale as col_scale |
| 226 | +FROM sys.tables t |
| 227 | +JOIN sys.schemas s ON t.schema_id = s.schema_id |
| 228 | +JOIN sys.columns c ON t.object_id = c.object_id |
| 229 | +JOIN sys.types ty ON c.system_type_id = ty.system_type_id |
| 230 | +JOIN cdc.change_tables ch ON t.object_id = ch.source_object_id |
| 231 | +"; |
| 232 | + fn get_value<'a, T: tiberius::FromSql<'a>>( |
| 233 | + row: &'a tiberius::Row, |
| 234 | + name: &'static str, |
| 235 | + ) -> Result<T, SqlServerError> { |
| 236 | + row.try_get(name)? |
| 237 | + .ok_or(SqlServerError::MissingColumn(name)) |
| 238 | + } |
| 239 | + |
| 240 | + let result = client.simple_query(GET_TABLES_QUERY).await?; |
| 241 | + |
| 242 | + // Group our columns by (schema, name). |
| 243 | + let mut tables = BTreeMap::default(); |
| 244 | + for row in result { |
| 245 | + let schema_name: Arc<str> = get_value::<&str>(&row, "schema_name")?.into(); |
| 246 | + let table_name: Arc<str> = get_value::<&str>(&row, "table_name")?.into(); |
| 247 | + let capture_instance: Arc<str> = get_value::<&str>(&row, "capture_instance")?.into(); |
| 248 | + |
| 249 | + let column_name = get_value::<&str>(&row, "col_name")?.into(); |
| 250 | + let column = SqlServerColumnRaw { |
| 251 | + name: Arc::clone(&column_name), |
| 252 | + data_type: get_value::<&str>(&row, "col_type")?.into(), |
| 253 | + is_nullable: get_value(&row, "col_nullable")?, |
| 254 | + max_length: get_value(&row, "col_max_length")?, |
| 255 | + precision: get_value(&row, "col_precision")?, |
| 256 | + scale: get_value(&row, "col_scale")?, |
| 257 | + }; |
| 258 | + |
| 259 | + let columns = tables |
| 260 | + .entry(( |
| 261 | + Arc::clone(&schema_name), |
| 262 | + Arc::clone(&table_name), |
| 263 | + Arc::clone(&capture_instance), |
| 264 | + )) |
| 265 | + .or_insert_with(|| Vec::default()); |
| 266 | + columns.push(column); |
| 267 | + } |
| 268 | + |
| 269 | + // Flatten into our raw Table description. |
| 270 | + let tables = tables |
| 271 | + .into_iter() |
| 272 | + .map(|((schema, name, capture_instance), columns)| { |
| 273 | + Ok::<_, SqlServerError>(SqlServerTableRaw { |
| 274 | + schema_name: schema, |
| 275 | + name, |
| 276 | + capture_instance, |
| 277 | + columns: columns.into(), |
| 278 | + is_cdc_enabled: true, |
| 279 | + }) |
| 280 | + }) |
| 281 | + .collect::<Result<_, _>>()?; |
| 282 | + |
| 283 | + Ok(tables) |
| 284 | +} |
| 285 | + |
| 286 | +/// Helper function to parse an expected result from a "system" query. |
| 287 | +fn check_system_result<'a, T>( |
| 288 | + result: &'a SmallVec<[tiberius::Row; 1]>, |
| 289 | + name: String, |
| 290 | + expected: T, |
| 291 | +) -> Result<(), SqlServerError> |
| 292 | +where |
| 293 | + T: tiberius::FromSql<'a> + Copy + fmt::Debug + fmt::Display + PartialEq, |
| 294 | +{ |
| 295 | + match &result[..] { |
| 296 | + [row] => { |
| 297 | + let result: Option<T> = row.try_get(0)?; |
| 298 | + if result == Some(expected) { |
| 299 | + Ok(()) |
| 300 | + } else { |
| 301 | + Err(SqlServerError::InvalidSystemSetting { |
| 302 | + name, |
| 303 | + expected: expected.to_string(), |
| 304 | + actual: format!("{result:?}"), |
| 305 | + }) |
| 306 | + } |
| 307 | + } |
| 308 | + other => Err(SqlServerError::InvariantViolated(format!( |
| 309 | + "expected 1 row, got {other:?}" |
| 310 | + ))), |
| 311 | + } |
| 312 | +} |
0 commit comments