Skip to main content

stackless_integrations/providers/planetscale/
postgresql.rs

1//! `planetscale/postgresql` integration.
2
3use std::collections::BTreeMap;
4
5use serde::Serialize;
6use stackless_stripe_projects::catalog::verify::CatalogService;
7use stackless_stripe_projects::provision::ProvisionContext;
8
9use super::FamilyResource;
10use crate::error::IntegrationError;
11use crate::hostable::{ConfigScope, Hostable, IntegrationHosting};
12use crate::registry;
13
14pub const RESOURCE_KIND: &str = "integration-planetscale-postgresql";
15
16#[derive(Debug, Serialize)]
17pub struct PlanetScalePostgresqlConfig {
18    pub cluster: String,
19    pub name: String,
20    pub region: String,
21    #[serde(skip_serializing_if = "Option::is_none")]
22    pub replicas: Option<i64>,
23}
24
25impl CatalogService for PlanetScalePostgresqlConfig {
26    const REFERENCE: &'static str = "planetscale/postgresql";
27}
28
29#[derive(Debug)]
30pub struct PlanetScalePostgresql;
31
32impl Hostable for PlanetScalePostgresql {
33    const PROVIDER: &'static str = "planetscale-postgresql";
34    const HOSTING: IntegrationHosting = IntegrationHosting::Managed;
35    const CONFIG_SCOPE: ConfigScope = ConfigScope::GlobalOnly;
36    const RESOURCE_KIND: &'static str = RESOURCE_KIND;
37    const OUTPUTS: &'static [&'static str] = &["url", "host", "database", "username", "password"];
38}
39
40impl FamilyResource for PlanetScalePostgresql {
41    type Config = PlanetScalePostgresqlConfig;
42    const PROVIDER_PREFIX: &'static str = "PLANETSCALE";
43    const OUTPUT_FIELDS: &'static [(&'static str, &'static str, bool)] = &[
44        ("URL", "url", true),
45        ("HOST", "host", false),
46        ("DATABASE", "database", true),
47        ("USERNAME", "username", true),
48        ("PASSWORD", "password", true),
49    ];
50
51    fn build_config(
52        ctx: &ProvisionContext<'_>,
53    ) -> Result<PlanetScalePostgresqlConfig, IntegrationError> {
54        let config = super::integration_config(ctx)?;
55        Ok(PlanetScalePostgresqlConfig {
56            cluster: super::interp_required(ctx, &config, "cluster")?,
57            name: super::interp_required(ctx, &config, "name")?,
58            region: super::interp_required(ctx, &config, "region")?,
59            replicas: super::int_optional(ctx, &config, "replicas")?,
60        })
61    }
62}
63
64pub fn validate_config(
65    name: &str,
66    config: &BTreeMap<String, toml::Value>,
67) -> Result<(), IntegrationError> {
68    registry::config_string(config, "cluster").map_err(|err| IntegrationError::ConfigInvalid {
69        location: format!("integrations.{name}.cluster"),
70        detail: err.to_string(),
71    })?;
72    registry::config_string(config, "name").map_err(|err| IntegrationError::ConfigInvalid {
73        location: format!("integrations.{name}.name"),
74        detail: err.to_string(),
75    })?;
76    registry::config_string(config, "region").map_err(|err| IntegrationError::ConfigInvalid {
77        location: format!("integrations.{name}.region"),
78        detail: err.to_string(),
79    })?;
80    let _ = (name, config);
81    Ok(())
82}
83
84#[cfg(test)]
85mod tests {
86    use super::*;
87    use crate::ProviderOps;
88    use crate::resource::ResourcePayload;
89    use stackless_core::def::StackDef;
90    use stackless_stripe_projects::stripe::StripeProjects;
91    use stackless_stripe_projects::test_support;
92
93    #[test]
94    fn config_matches_catalog() {
95        const FIXTURE: &str = include_str!(concat!(
96            env!("CARGO_MANIFEST_DIR"),
97            "/../stackless-stripe-projects/tests/fixtures/catalog.json"
98        ));
99        let catalog = stackless_stripe_projects::Catalog::from_json_envelope(FIXTURE).unwrap();
100        let failures = stackless_stripe_projects::verify_service(
101            &catalog,
102            &PlanetScalePostgresqlConfig {
103                cluster: "PS-5".into(),
104                name: "test-name".into(),
105                region: "aws-ap-northeast".into(),
106                replicas: None,
107            },
108        );
109        assert!(
110            failures.is_empty(),
111            "planetscale/postgresql catalog gaps:\n{}",
112            failures.join("\n")
113        );
114    }
115
116    const CATALOG_ENVELOPE: &str = r##"{"ok":true,"command":"projects catalog","data":{"last_updated":"2026-07-11T00:00:00Z","services":[{"id":"prvsvc_postgresql","object":"v2.provisioning.provider_service_detail","provider_id":"prvdr_planetscale","provider_name":"PlanetScale","service_id":"postgresql","categories":["database"],"kind":"deployable","scope":"project","availability":"available","development":false,"livemode":true,"pricing":{"type":"paid"},"configuration_schema":{"properties":{"cluster":{"description":"Cluster size","enum":["PS-5","PS-10","PS-20","PS-40","PS-80","PS-160","PS-320"],"type":"string"},"name":{"description":"Database name.","maxLength":63,"minLength":2,"pattern":"^[a-z0-9][a-z0-9_-]*[a-z0-9]$","type":"string"},"region":{"description":"Deployment region (prefixed with cloud provider, e.g., aws-us-east, gcp-us-central1)","enum":["aws-ap-northeast","aws-ap-south","aws-ap-southeast","aws-ap-southeast-2","aws-ca-central-1","aws-eu-central","aws-eu-west","aws-eu-west-2","aws-sa-east-1","aws-us-east","aws-us-east-2","aws-us-west","gcp-asia-northeast3","gcp-europe-west1","gcp-europe-west4","gcp-northamerica-northeast1","gcp-us-central1","gcp-us-east1","gcp-us-east4"],"type":"string"},"replicas":{"default":0,"description":"Number of replicas (0 for single node, 2+ for high availability)","maximum":9,"minimum":0,"type":"integer"}},"required":["name","cluster","region"],"type":"object"}}]}}"##;
117
118    fn test_def() -> StackDef {
119        StackDef::parse(
120            r#"
121[stack]
122name = "atto"
123[stack.projects.stripe]
124project = "project_1"
125[integrations.res]
126provider = "planetscale-postgresql"
127cluster = "PS-5"
128name = "test-name"
129region = "aws-ap-northeast"
130[services.api]
131source = { repo = "r", ref = "main" }
132env = { OUT = "${integrations.res.url}" }
133health = { path = "/health" }
134[services.api.local]
135run = "true"
136"#,
137        )
138        .unwrap()
139    }
140
141    #[tokio::test]
142    async fn provision_records_outputs() {
143        let runner = test_support::provision_script(
144            CATALOG_ENVELOPE,
145            serde_json::json!({"PLANETSCALE_URL": "val_url", "PLANETSCALE_HOST": "val_host", "PLANETSCALE_DATABASE": "val_database", "PLANETSCALE_USERNAME": "val_username", "PLANETSCALE_PASSWORD": "val_password"}),
146            0,
147        );
148        let dir = tempfile::tempdir().unwrap();
149        std::fs::write(
150            dir.path().join("stackless.toml"),
151            "[stack]\nname=\"atto\"\n",
152        )
153        .unwrap();
154        let stripe = StripeProjects::new(&runner, dir.path());
155
156        let resource = PlanetScalePostgresql
157            .provision(
158                &stripe.as_dyn(),
159                &test_def(),
160                dir.path(),
161                "demo",
162                "res",
163                "local",
164                false,
165            )
166            .await
167            .unwrap();
168        assert_eq!(resource.resource_kind, "integration-planetscale-postgresql");
169        let payload: ResourcePayload = serde_json::from_str(&resource.payload).unwrap();
170        assert_eq!(payload.outputs["url"], "val_url");
171    }
172}