|
| 1 | +# Schema |
| 2 | + |
| 3 | +The driver is capable of fetching database schema and presenting it to its users. |
| 4 | + |
| 5 | +## Fetching schema |
| 6 | + |
| 7 | +Fetching database schema occurs periodically, but it can also be done on-demand. In order to fetch the newest database schema, one can call `refresh_metadata()` on a Session instance: |
| 8 | +```rust |
| 9 | +# extern crate scylla; |
| 10 | +# extern crate tokio; |
| 11 | +# use std::error::Error; |
| 12 | +# use scylla::{Session, SessionBuilder}; |
| 13 | + |
| 14 | +#[tokio::main] |
| 15 | +async fn main() -> Result<(), Box<dyn Error>> { |
| 16 | + let uri = std::env::var("SCYLLA_URI") |
| 17 | + .unwrap_or_else(|_| "127.0.0.1:9042".to_string()); |
| 18 | + |
| 19 | + let session: Session = SessionBuilder::new().known_node(uri).build().await?; |
| 20 | + // Schema metadata will be fetched below |
| 21 | + session.refresh_metadata().await?; |
| 22 | + Ok(()) |
| 23 | +} |
| 24 | +``` |
| 25 | + |
| 26 | +## Inspecting schema |
| 27 | + |
| 28 | +Once fetched, a snapshot of cluster's schema can be examined. The following information can be obtained: |
| 29 | + - keyspace |
| 30 | + - tables belonging to the keyspace |
| 31 | + - materialized views belonging to the keyspace |
| 32 | + - replication strategy |
| 33 | + - user-defined types |
| 34 | + - table/view |
| 35 | + - primary key definition |
| 36 | + - columns |
| 37 | + - partitioner type |
| 38 | + |
| 39 | +Example showing how to print obtained schema information: |
| 40 | + |
| 41 | +```rust |
| 42 | +# extern crate scylla; |
| 43 | +# extern crate tokio; |
| 44 | +# use std::error::Error; |
| 45 | +# use scylla::{Session, SessionBuilder}; |
| 46 | + |
| 47 | +#[tokio::main] |
| 48 | +async fn main() -> Result<(), Box<dyn Error>> { |
| 49 | + let uri = std::env::var("SCYLLA_URI") |
| 50 | + .unwrap_or_else(|_| "127.0.0.1:9042".to_string()); |
| 51 | + |
| 52 | + let session: Session = SessionBuilder::new().known_node(uri).build().await?; |
| 53 | + // Schema metadata will be fetched below |
| 54 | + session.refresh_metadata().await?; |
| 55 | + |
| 56 | + let cluster_data = &session.get_cluster_data(); |
| 57 | + let keyspaces = &cluster_data.get_keyspace_info(); |
| 58 | + |
| 59 | + for (keyspace_name, keyspace_info) in keyspaces.iter() { |
| 60 | + println!("Keyspace {}:", keyspace_name); |
| 61 | + println!("\tTables: {:#?}", keyspace_info.tables); |
| 62 | + println!("\tViews: {:#?}", keyspace_info.views); |
| 63 | + println!("\tUDTs: {:#?}", keyspace_info.user_defined_types); |
| 64 | + } |
| 65 | + |
| 66 | + Ok(()) |
| 67 | +} |
| 68 | +``` |
0 commit comments