Skip to content

Commit 332a629

Browse files
committed
feat(sdk): allow MigrationAction to be configurable per runtime name
1 parent 57eb593 commit 332a629

File tree

10 files changed

+89
-26
lines changed

10 files changed

+89
-26
lines changed

examples/deploy/deploy.mjs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,7 @@ const tg = await typegraph({
7373

7474
const artifactsConfig = {
7575
prismaMigration: {
76-
action: {
76+
globalAction: {
7777
create: true,
7878
reset: false
7979
},

examples/deploy/deploy.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,8 @@ def deploy_example_python(g: Graph):
7878

7979
config_params = MigrationConfig(
8080
migration_dir=path.join("prisma-migrations", tg.name),
81-
action=MigrationAction(create=True, reset=True),
81+
global_action=MigrationAction(create=True, reset=True), # all runtimes
82+
runtime_actions=None, # usually set from the cli
8283
)
8384
artifacts_config = ArtifactResolutionConfig(
8485
prefix=None, dir=None, prisma_migration=config_params

meta-cli/src/com/server.rs

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,22 @@ async fn config(req: HttpRequest) -> impl Responder {
5757

5858
let endpoint = ServerStore::get_endpoint();
5959
let secrets = ServerStore::get_secrets();
60-
let migration_action = ServerStore::get_migration_action(&parsed.typegraph_path);
60+
let migration_action_glob = ServerStore::get_migration_action_glob();
61+
62+
let mut migration_action_per_rt = vec![];
63+
if let Some(per_rt_actions) = ServerStore::get_runtime_migration_actions(&parsed.typegraph_path)
64+
{
65+
migration_action_per_rt =
66+
per_rt_actions
67+
.iter()
68+
.fold(migration_action_per_rt, |mut acc, local_cfg| {
69+
acc.push(json!([
70+
local_cfg.runtime_name.clone(),
71+
local_cfg.action.clone()
72+
]));
73+
acc
74+
});
75+
}
6176

6277
let prefix = ServerStore::get_prefix();
6378
match ServerStore::get_config() {
@@ -76,7 +91,8 @@ async fn config(req: HttpRequest) -> impl Responder {
7691
"prismaMigration": {
7792
// only the cli is aware of the convention migrationDir := tg_workdir + config_folder + tg_name
7893
"migrationDir": config.prisma_migrations_dir_rel(&parsed.typegraph),
79-
"action": serde_json::to_value(migration_action).unwrap()
94+
"globalAction": migration_action_glob,
95+
"runtimeAction": migration_action_per_rt
8096
},
8197
},
8298
});

meta-cli/src/com/store.rs

Lines changed: 19 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -51,12 +51,20 @@ pub struct MigrationAction {
5151
pub create: bool,
5252
}
5353

54+
#[derive(Default, Serialize, Clone, Debug)]
55+
pub struct RuntimeMigrationAction {
56+
pub runtime_name: String,
57+
pub action: MigrationAction,
58+
}
59+
5460
#[derive(Default, Debug)]
5561
pub struct ServerStore {
5662
config: Option<Config>,
5763
command: Option<Command>,
64+
/// default (all)
5865
migration_action_glob: MigrationAction,
59-
migration_action: HashMap<PathBuf, Arc<MigrationAction>>,
66+
/// per runtime per typegraph
67+
migration_action: HashMap<PathBuf, Arc<Vec<RuntimeMigrationAction>>>,
6068
secrets: HashMap<String, String>,
6169
endpoint: Endpoint,
6270
prefix: Option<String>,
@@ -129,22 +137,27 @@ impl ServerStore {
129137
with_store(|s| s.migration_action_glob.to_owned())
130138
}
131139

132-
pub fn set_migration_action(tg_path: PathBuf, option: MigrationAction) {
140+
pub fn set_migration_action(tg_path: PathBuf, rt_migration_option: RuntimeMigrationAction) {
133141
with_store_mut(|s| {
134-
s.migration_action.insert(tg_path, option.into());
142+
let mut items = vec![];
143+
if let Some(actions) = s.migration_action.get(&tg_path) {
144+
items = actions.as_ref().clone();
145+
}
146+
items.push(rt_migration_option);
147+
s.migration_action.insert(tg_path, items.into());
135148
})
136149
}
137150

138-
pub fn get_migration_action(tg_path: &PathBuf) -> MigrationAction {
151+
pub fn get_runtime_migration_actions(tg_path: &PathBuf) -> Option<Vec<RuntimeMigrationAction>> {
139152
with_store(|s| {
140153
if let Some(mig_action) = s.migration_action.get(tg_path) {
141154
println!(
142155
"Specific migration action was defined for {}",
143156
tg_path.display()
144157
);
145-
return mig_action.as_ref().to_owned();
158+
return Some(mig_action.as_ref().to_owned());
146159
}
147-
s.migration_action_glob.to_owned()
160+
None
148161
})
149162
}
150163

meta-cli/src/deploy/push/migration_resolution.rs

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ use anyhow::Result;
88
use colored::Colorize;
99

1010
use crate::{
11-
com::store::ServerStore,
11+
com::store::{MigrationAction, RuntimeMigrationAction, ServerStore},
1212
deploy::actors::{
1313
console::{
1414
input::{ConfirmHandler, OptionLabel, SelectOption},
@@ -24,16 +24,26 @@ use crate::{
2424
pub struct ConfirmDatabaseResetRequired {
2525
pub typegraph_path: PathBuf,
2626
pub loader: Addr<LoaderActor>,
27+
pub runtime_name: String,
2728
}
2829

2930
impl ConfirmHandler for ConfirmDatabaseResetRequired {
3031
fn on_confirm(&self) {
3132
let tg_path = self.typegraph_path.clone();
33+
let runtime_name = self.runtime_name.clone();
3234

3335
// reset
34-
let mut option = ServerStore::get_migration_action(&tg_path);
35-
option.reset = true;
36-
ServerStore::set_migration_action(tg_path.clone(), option);
36+
let glob_cfg = ServerStore::get_migration_action_glob();
37+
ServerStore::set_migration_action(
38+
tg_path.clone(),
39+
RuntimeMigrationAction {
40+
runtime_name,
41+
action: MigrationAction {
42+
reset: true, // !
43+
create: glob_cfg.create,
44+
},
45+
},
46+
);
3747

3848
// reload
3949
self.loader.do_send(LoadModule(tg_path.into()));

meta-cli/src/deploy/push/pusher.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -235,6 +235,7 @@ async fn handle_database_reset(
235235
)
236236
.interact(Box::new(ConfirmDatabaseResetRequired {
237237
typegraph_path: sdk_response.typegraph_path,
238+
runtime_name,
238239
loader,
239240
}))
240241
.await?;

typegraph/core/src/utils/postprocess/prisma_rt.rs

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,8 @@ use common::typegraph::Typegraph;
88

99
use crate::utils::fs_host;
1010
use crate::utils::postprocess::PostProcessor;
11-
use crate::wit::core::MigrationConfig;
12-
use crate::wit::metatype::typegraph::host::path_exists;
11+
use crate::wit::core::{MigrationAction, MigrationConfig};
12+
use crate::wit::metatype::typegraph::host::{eprint, path_exists};
1313

1414
pub struct PrismaProcessor {
1515
config: MigrationConfig,
@@ -36,6 +36,7 @@ impl PrismaProcessor {
3636
if let TGRuntime::Known(Prisma(rt_data)) = rt {
3737
let rt_name = &rt_data.name;
3838
let path = base_migration_path.join(rt_name);
39+
let action = self.get_action_by_rt_name(rt_name);
3940

4041
rt_data.migration_options = Some(MigrationOptions {
4142
migration_files: {
@@ -48,8 +49,8 @@ impl PrismaProcessor {
4849
false => None,
4950
}
5051
},
51-
create: self.config.action.create,
52-
reset: self.config.action.reset,
52+
create: action.create,
53+
reset: action.reset,
5354
});
5455
}
5556
}
@@ -62,4 +63,16 @@ impl PrismaProcessor {
6263
let path = fs_host::cwd()?.join(PathBuf::from(migration_dir));
6364
Ok(path)
6465
}
66+
67+
/// Get migration action from runtime_name (usually set from the cli)
68+
/// If nothing is found, find the global action config (set initially)
69+
pub fn get_action_by_rt_name(&self, name: &str) -> MigrationAction {
70+
if let Some(actions) = self.config.runtime_actions.clone() {
71+
if let Some(action) = actions.iter().find(|(rt, _)| rt.eq(name)) {
72+
eprint(&format!("Specific migration action found for {name}"));
73+
return action.1;
74+
}
75+
}
76+
self.config.global_action
77+
}
6578
}

typegraph/core/wit/typegraph.wit

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,8 @@ interface core {
4242

4343
record migration-config {
4444
migration-dir: string,
45-
action: migration-action
45+
global-action: migration-action, // global config (all runtimes)
46+
runtime-actions: option<list<tuple<string, migration-action>>> // config per runtime name (override global-action)
4647
}
4748

4849
record artifact-resolution-config {

typegraph/python/typegraph/graph/tg_manage.py

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -142,6 +142,8 @@ def request_config(self) -> CLIConfigRequest:
142142
auth = BasicAuth(raw_auth["username"], raw_auth["password"])
143143

144144
artifact_config_raw = cli_res["artifactsConfig"]
145+
migration_action_raw = artifact_config_raw["prismaMigration"]
146+
145147
return CLIConfigRequest(
146148
typegate=Typegate(endpoint=cli_res["typegate"]["endpoint"], auth=auth),
147149
prefix=prefix,
@@ -150,12 +152,13 @@ def request_config(self) -> CLIConfigRequest:
150152
dir=artifact_config_raw["dir"],
151153
prefix=prefix,
152154
prisma_migration=MigrationConfig(
153-
action=MigrationAction(
154-
create=artifact_config_raw["prismaMigration"]["action"][
155-
"create"
156-
],
157-
reset=artifact_config_raw["prismaMigration"]["action"]["reset"],
155+
global_action=json_to_mig_action(
156+
migration_action_raw["globalAction"]
158157
),
158+
runtime_actions=[
159+
(rt, json_to_mig_action(act))
160+
for [rt, act] in migration_action_raw["runtimeAction"]
161+
],
159162
migration_dir=artifact_config_raw["prismaMigration"][
160163
"migrationDir"
161164
],
@@ -174,7 +177,6 @@ def relay_result_to_cli(self, initiator: Command, fn: callable):
174177
response["data"] = json.loads(res) if isinstance(res, str) else res
175178
except Exception as e:
176179
response["error"] = str(e)
177-
178180
req = request.Request(
179181
url=f"{self.endpoint}/response",
180182
method="POST",
@@ -189,3 +191,10 @@ def exist_and_not_null(obj: dict, field: str):
189191
if field in obj:
190192
return obj[field] is not None
191193
return False
194+
195+
196+
def json_to_mig_action(obj: dict) -> MigrationAction:
197+
return MigrationAction(
198+
create=obj["create"],
199+
reset=obj["reset"],
200+
)

typegraph/python/typegraph/graph/typegraph.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,6 @@ def expose(
7878
default_policy: Optional[PolicySpec] = None,
7979
**kwargs: ExposeItem,
8080
):
81-
print(str(kwargs))
8281
res = core.expose(
8382
store,
8483
[(k, v.id) for k, v in kwargs.items()],

0 commit comments

Comments
 (0)