pub trait SpannerResource {
fn name(&self) -> &str;
fn resources_path(&self) -> String;
fn id(&self) -> String {
format!("{}/{}", self.resources_path(), self.name())
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProjectId(String);
impl ProjectId {
pub fn new(name: &str) -> Self {
Self(name.to_string())
}
}
impl SpannerResource for ProjectId {
fn name(&self) -> &str {
&self.0
}
fn resources_path(&self) -> String {
"projects".to_string()
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InstanceId(ProjectId, String);
impl InstanceId {
pub fn new(project: ProjectId, name: &str) -> Self {
Self(project, name.to_string())
}
pub fn project(&self) -> &ProjectId {
&self.0
}
}
impl SpannerResource for InstanceId {
fn name(&self) -> &str {
&self.1
}
fn resources_path(&self) -> String {
format!("{}/instances", self.0.id())
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DatabaseId(InstanceId, String);
impl DatabaseId {
pub fn new(instance: InstanceId, name: &str) -> Self {
Self(instance, name.to_string())
}
}
impl SpannerResource for DatabaseId {
fn name(&self) -> &str {
&self.1
}
fn resources_path(&self) -> String {
format!("{}/databases", self.0.id())
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_project_id() {
let project_id = ProjectId::new("test-project");
assert_eq!(project_id.name(), "test-project");
assert_eq!(project_id.resources_path(), "projects".to_string());
assert_eq!(project_id.id(), "projects/test-project".to_string());
}
#[test]
fn test_instance_id() {
let instance_id = InstanceId::new(ProjectId::new("test-project"), "test-instance");
assert_eq!(instance_id.name(), "test-instance");
assert_eq!(
instance_id.resources_path(),
"projects/test-project/instances"
);
assert_eq!(
instance_id.id(),
"projects/test-project/instances/test-instance"
);
}
#[test]
fn test_database_id() {
let database_id = DatabaseId::new(
InstanceId::new(ProjectId::new("test-project"), "test-instance"),
"test-database",
);
assert_eq!(database_id.name(), "test-database");
assert_eq!(
database_id.resources_path(),
"projects/test-project/instances/test-instance/databases"
);
assert_eq!(
database_id.id(),
"projects/test-project/instances/test-instance/databases/test-database"
);
}
}