-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabases.rs
More file actions
1499 lines (1377 loc) · 51.9 KB
/
Copy pathdatabases.rs
File metadata and controls
1499 lines (1377 loc) · 51.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use crate::sdk::{Api, ApiError, block, none_if_404};
use indicatif::{ProgressBar, ProgressStyle};
use serde::{Deserialize, Serialize};
use std::path::Path;
const DEFAULT_SCHEMA: &str = "public";
/// CLI output shape for `databases list` rows. A curated, stably-ordered view
/// mapped from the SDK's `DatabaseSummary` (see the `From` impl) so the
/// `-o json`/`-o yaml` contract stays decoupled from generated-model field
/// order and nullability.
#[derive(Clone, Debug, Serialize, PartialEq, Eq)]
struct DatabaseSummary {
id: String,
#[serde(default)]
name: Option<String>,
#[serde(default)]
default_catalog: Option<String>,
}
/// CLI output shape for `databases get`. A curated, stably-ordered view mapped
/// from the SDK's `DatabaseDetailResponse` (see the `From` impl), keeping the
/// `-o json`/`-o yaml` contract independent of the generated model's field order
/// and `Option<Option<_>>` nullability.
#[derive(Clone, Debug, Serialize, PartialEq, Eq)]
pub struct Database {
pub id: String,
#[serde(default)]
pub name: Option<String>,
#[serde(default)]
pub default_catalog: Option<String>,
pub default_connection_id: String,
#[serde(default)]
pub expires_at: Option<String>,
#[serde(default)]
attachments: Vec<DatabaseAttachment>,
}
#[derive(Clone, Debug, Serialize, PartialEq, Eq)]
struct DatabaseAttachment {
connection_id: String,
alias: Option<String>,
}
#[derive(Deserialize)]
struct InfoTable {
#[allow(dead_code)]
connection: String,
schema: String,
table: String,
synced: bool,
last_sync: Option<String>,
}
#[derive(Deserialize, Serialize)]
struct TableRow {
full_name: String,
schema: String,
table: String,
synced: bool,
last_sync: Option<String>,
}
#[derive(Deserialize, Serialize)]
struct CreateDatabaseResponse {
id: String,
#[serde(default)]
name: Option<String>,
#[serde(default)]
default_catalog: Option<String>,
default_connection_id: String,
#[serde(default)]
expires_at: Option<String>,
}
/// Response shape of `POST /v1/auth/database`.
#[derive(Deserialize)]
struct DatabaseTokenResponse {
token: String,
refresh_token: String,
database_id: String,
expires_in: u64,
refresh_expires_in: u64,
}
#[derive(Deserialize)]
struct LoadManagedTableResponse {
#[allow(dead_code)]
connection_id: String,
schema_name: String,
table_name: String,
row_count: u64,
#[allow(dead_code)]
arrow_schema_json: String,
}
impl From<hotdata::models::DatabaseDetailResponse> for Database {
/// Map the SDK's typed detail response into the CLI output shape, flattening
/// the SDK's `Option<Option<_>>` nullable fields and wrapping the
/// SDK-required `default_catalog` as `Some`.
fn from(d: hotdata::models::DatabaseDetailResponse) -> Self {
Database {
id: d.id,
name: d.name.flatten(),
default_catalog: Some(d.default_catalog),
default_connection_id: d.default_connection_id,
expires_at: d.expires_at.flatten(),
attachments: d
.attachments
.into_iter()
.map(|a| DatabaseAttachment {
connection_id: a.connection_id,
alias: a.alias.flatten(),
})
.collect(),
}
}
}
impl From<hotdata::models::DatabaseSummary> for DatabaseSummary {
/// Map the SDK's typed summary into the CLI's list-row output shape.
fn from(s: hotdata::models::DatabaseSummary) -> Self {
DatabaseSummary {
id: s.id,
name: s.name.flatten(),
default_catalog: Some(s.default_catalog),
}
}
}
/// Fetch a database by id through the SDK's typed `databases().get` handle.
///
/// The handle owns auth, scope headers, URL construction, and percent-encoding
/// of the id segment, so callers no longer hand-roll the path. The result is
/// mapped into the CLI's `Database`.
pub(crate) fn get_database(api: &Api, id: &str) -> Result<Database, ApiError> {
block(api.client().databases().get(id)).map(Database::from)
}
/// List databases through the SDK's typed `databases().list` handle, mapped
/// into the CLI's summary rows.
fn list_database_summaries(api: &Api) -> Result<Vec<DatabaseSummary>, ApiError> {
block(api.client().databases().list())
.map(|r| r.databases.into_iter().map(DatabaseSummary::from).collect())
}
fn fetch_database(api: &Api, id: &str) -> Database {
get_database(api, id).unwrap_or_else(|e| e.exit())
}
pub fn try_resolve_database(api: &Api, id_or_name: &str) -> Result<Database, String> {
// Try a direct id lookup first — avoids the list round-trip for the common
// case. The typed handle percent-encodes the id segment, so names with
// spaces or other URL-unsafe characters resolve (or 404 cleanly) without
// manual encoding before the list fallback runs.
if let Some(db) = none_if_404(get_database(api, id_or_name)).unwrap_or_else(|e| e.exit()) {
return Ok(db);
}
// Fall back to listing — prefer catalog alias match, then name.
let databases = list_database_summaries(api).unwrap_or_else(|e| e.exit());
let catalog_matches: Vec<&DatabaseSummary> = databases
.iter()
.filter(|d| d.default_catalog.as_deref() == Some(id_or_name))
.collect();
if !catalog_matches.is_empty() {
return match catalog_matches.len() {
1 => Ok(fetch_database(api, &catalog_matches[0].id)),
_ => Err(format!(
"multiple databases have catalog '{}' — use the database id instead",
id_or_name
)),
};
}
let name_matches: Vec<&DatabaseSummary> = databases
.iter()
.filter(|d| d.name.as_deref() == Some(id_or_name))
.collect();
match name_matches.len() {
0 => Err(format!(
"no database with id, catalog, or name '{id_or_name}'"
)),
1 => Ok(fetch_database(api, &name_matches[0].id)),
_ => Err(format!(
"multiple databases have name '{}' — use the database id instead",
id_or_name
)),
}
}
pub fn resolve_database(api: &Api, id_or_name: &str) -> Database {
match try_resolve_database(api, id_or_name) {
Ok(db) => db,
Err(e) => {
use crossterm::style::Stylize;
eprintln!("{}", format!("error: {e}").red());
std::process::exit(1);
}
}
}
fn schema_name(schema: Option<&str>) -> &str {
schema.unwrap_or(DEFAULT_SCHEMA)
}
/// Build the request body for `POST /v1/databases`.
pub fn create_database_request(
name: Option<&str>,
catalog: Option<&str>,
schema: &str,
tables: &[String],
expires_at: Option<&str>,
) -> serde_json::Value {
let mut req = serde_json::Map::new();
if let Some(n) = name {
req.insert("name".to_string(), serde_json::Value::String(n.to_string()));
}
if let Some(c) = catalog {
req.insert(
"default_catalog".to_string(),
serde_json::Value::String(c.to_string()),
);
}
if !tables.is_empty() {
// Group tables by schema, preserving insertion order.
// Dot-notation entries (e.g. "raw.raw_orders") use the named schema;
// bare names fall back to the `schema` argument.
let mut schema_tables: Vec<(String, Vec<String>)> = Vec::new();
for t in tables {
let (s, table_name) = match t.split_once('.') {
Some((s, tbl)) => (s.to_string(), tbl.to_string()),
None => (schema.to_string(), t.to_string()),
};
if let Some(entry) = schema_tables.iter_mut().find(|(n, _)| n == &s) {
entry.1.push(table_name);
} else {
schema_tables.push((s, vec![table_name]));
}
}
let schemas_json: Vec<serde_json::Value> = schema_tables
.into_iter()
.map(|(s, tbls)| {
serde_json::json!({
"name": s,
"tables": tbls.iter().map(|t| serde_json::json!({ "name": t })).collect::<Vec<_>>()
})
})
.collect();
req.insert(
"schemas".to_string(),
serde_json::Value::Array(schemas_json),
);
}
if let Some(exp) = expires_at {
req.insert(
"expires_at".to_string(),
serde_json::Value::String(exp.to_string()),
);
}
serde_json::Value::Object(req)
}
/// Build the typed `CreateDatabaseRequest` for the SDK's `databases().create`
/// handle, reusing [`create_database_request`] as the single source of truth for
/// the body shape. The delete+recreate path still consumes the raw JSON form
/// (it inspects raw error bodies), so the JSON builder stays; this just adapts
/// it for the typed call sites.
fn create_database_typed_request(
name: Option<&str>,
catalog: Option<&str>,
schema: &str,
tables: &[String],
expires_at: Option<&str>,
) -> hotdata::models::CreateDatabaseRequest {
serde_json::from_value(create_database_request(
name, catalog, schema, tables, expires_at,
))
.expect("create_database_request always emits a valid CreateDatabaseRequest body")
}
pub fn managed_table_load_path(connection_id: &str, schema: &str, table: &str) -> String {
format!("/connections/{connection_id}/schemas/{schema}/tables/{table}/loads")
}
pub fn managed_table_delete_path(connection_id: &str, schema: &str, table: &str) -> String {
format!("/connections/{connection_id}/schemas/{schema}/tables/{table}")
}
pub fn load_table_request(upload_id: &str) -> serde_json::Value {
serde_json::json!({
"mode": "replace",
"upload_id": upload_id,
})
}
/// Returns true when `path` looks like a parquet file by extension.
pub fn is_parquet_path(path: &str) -> bool {
path.to_ascii_lowercase().ends_with(".parquet")
|| Path::new(path).extension().and_then(|e| e.to_str()) == Some("parquet")
}
fn table_rows(catalog: &str, tables: Vec<InfoTable>) -> Vec<TableRow> {
tables
.into_iter()
.map(|t| TableRow {
full_name: format!("{catalog}.{}.{}", t.schema, t.table),
schema: t.schema,
table: t.table,
synced: t.synced,
last_sync: t.last_sync,
})
.collect()
}
fn finish_upload(
api: &Api,
reader: impl std::io::Read + Send + 'static,
size: Option<u64>,
pb: &ProgressBar,
) -> String {
// Stream the body to `POST /v1/files` through the SDK seam, which drives the
// SDK's `upload_stream` on a dedicated no-timeout client (a 10 GB+ parquet
// far outlives the shared 300s request timeout) and bridges this blocking,
// progress-wrapped `reader` into the async byte stream the SDK consumes.
// `size` becomes the `Content-Length` so the server fast-fails an oversized
// upload before writing bytes; the `--url` source may not know it, hence
// `Option`. Carries the same auth + scope headers as every other SDK call.
let result = api.upload_stream(reader, size, "application/octet-stream");
pb.finish_and_clear();
match result {
Ok(id) => id,
Err(e) => e.exit(),
}
}
fn upload_parquet_file(api: &Api, path: &str) -> String {
if !is_parquet_path(path) {
eprintln!(
"error: managed table loads require a parquet file (got '{}'). \
Convert your data to parquet or use `hotdata datasets create` for CSV/JSON.",
path
);
std::process::exit(1);
}
let f = match std::fs::File::open(path) {
Ok(f) => f,
Err(e) => {
eprintln!("error opening file '{path}': {e}");
std::process::exit(1);
}
};
let file_size = f.metadata().map(|m| m.len()).unwrap_or(0);
let pb = ProgressBar::new(file_size);
pb.set_style(
ProgressStyle::with_template(
"{spinner:.green} [{bar:40.cyan/blue}] {bytes}/{total_bytes} ({eta})",
)
.unwrap()
.progress_chars("=>-"),
);
let reader = pb.wrap_read(f);
finish_upload(api, reader, Some(file_size), &pb)
}
fn upload_parquet_url(api: &Api, url: &str) -> String {
if !is_parquet_path(url) {
eprintln!(
"error: managed table loads require a parquet URL ending in .parquet (got '{url}')."
);
std::process::exit(1);
}
let resp = match reqwest::blocking::get(url) {
Ok(r) => r,
Err(e) => {
eprintln!("error fetching '{url}': {e}");
std::process::exit(1);
}
};
if !resp.status().is_success() {
eprintln!(
"error: remote server returned {} for '{url}'",
resp.status()
);
std::process::exit(1);
}
let content_length = resp.content_length();
let pb = match content_length {
Some(len) => {
let pb = ProgressBar::new(len);
pb.set_style(
ProgressStyle::with_template(
"{spinner:.green} [{bar:40.cyan/blue}] {bytes}/{total_bytes} ({eta})",
)
.unwrap()
.progress_chars("=>-"),
);
pb
}
None => {
let pb = ProgressBar::new_spinner();
pb.set_style(
ProgressStyle::with_template("{spinner:.green} {bytes} downloaded ({elapsed})")
.unwrap(),
);
pb
}
};
let reader = pb.wrap_read(resp);
finish_upload(api, reader, content_length, &pb)
}
fn collect_tables(api: &Api, connection_id: &str, schema: Option<&str>) -> Vec<InfoTable> {
let mut out = Vec::new();
let mut cursor: Option<String> = None;
loop {
let resp = crate::sdk::block(api.client().information_schema().get(
Some(connection_id),
schema,
None,
None,
None,
cursor.as_deref(),
))
.unwrap_or_else(|e| e.exit());
out.extend(resp.tables.into_iter().map(|t| InfoTable {
connection: t.connection,
schema: t.schema,
table: t.table,
synced: t.synced,
last_sync: t.last_sync.flatten(),
}));
if !resp.has_more {
break;
}
let Some(c) = resp.next_cursor.flatten() else {
break;
};
cursor = Some(c);
}
out.sort_by(|a, b| a.schema.cmp(&b.schema).then_with(|| a.table.cmp(&b.table)));
out
}
pub fn list(workspace_id: &str, format: &str) {
let api = Api::new(Some(workspace_id));
let databases = list_database_summaries(&api).unwrap_or_else(|e| e.exit());
match format {
"json" => println!("{}", serde_json::to_string_pretty(&databases).unwrap()),
"yaml" => print!("{}", serde_yaml::to_string(&databases).unwrap()),
"table" => {
if databases.is_empty() {
use crossterm::style::Stylize;
eprintln!("{}", "No databases found.".dark_grey());
eprintln!(
"{}",
"Create one with: hotdata databases create --catalog <alias>".dark_grey()
);
} else {
let current = crate::config::load_current_database("default", workspace_id);
let rows: Vec<Vec<String>> = databases
.iter()
.map(|d| {
let marker = if current.as_deref() == Some(d.id.as_str()) {
"*"
} else {
""
};
vec![
marker.to_string(),
d.id.clone(),
d.name.as_deref().unwrap_or("-").to_string(),
]
})
.collect();
crate::table::print(&["", "ID", "NAME"], &rows);
}
}
_ => unreachable!(),
}
}
pub fn get(workspace_id: &str, id_or_name: &str, format: &str) {
let api = Api::new(Some(workspace_id));
let db = resolve_database(&api, id_or_name);
match format {
"json" => println!("{}", serde_json::to_string_pretty(&db).unwrap()),
"yaml" => print!("{}", serde_yaml::to_string(&db).unwrap()),
"table" => {
use crossterm::style::Stylize;
let label = |l: &str| format!("{:<24}", l).dark_grey().to_string();
println!("{}{}", label("id:"), db.id.clone().dark_cyan());
if let Some(n) = &db.name {
println!("{}{}", label("name:"), n.clone().cyan());
}
if let Some(c) = &db.default_catalog {
println!("{}{}", label("catalog:"), c.clone().cyan());
}
println!(
"{}{}",
label("default_connection_id:"),
db.default_connection_id.clone().dark_cyan()
);
let catalog = db
.default_catalog
.as_deref()
.or(db.name.as_deref())
.unwrap_or("default");
println!(
"{}{}",
label("sql_prefix:"),
format!(
"{catalog}.{{schema}}.{{table}} (pass X-Database-Id header when querying)"
)
.green()
);
if !db.attachments.is_empty() {
println!("{}({})", label("attached catalogs:"), db.attachments.len());
for a in &db.attachments {
let alias = a
.alias
.as_deref()
.map(|al| format!(" as {al}"))
.unwrap_or_default();
println!(
" {}{}",
a.connection_id.clone().dark_cyan(),
alias.dark_grey()
);
}
}
}
_ => unreachable!(),
}
}
/// Create a database and return its id. Used by `run` when no
/// `--database` is given. Mirrors `create`'s request path but returns
/// the id instead of printing.
fn create_and_return_id(
api: &Api,
name: Option<&str>,
schema: &str,
tables: &[String],
expires_at: Option<&str>,
) -> String {
let request = create_database_typed_request(name, None, schema, tables, expires_at);
block(api.client().databases().create(request))
.unwrap_or_else(|e| e.exit())
.id
}
/// Mint a database-scoped JWT for an existing database id via
/// `POST /v1/auth/database` (grant_type=existing_database). The call
/// doubles as an existence + access check (the server 404s an unknown
/// or unreachable database).
fn mint_database_token(api: &Api, database_id: &str) -> DatabaseTokenResponse {
let body = serde_json::json!({
"grant_type": "existing_database",
"database_id": database_id,
});
let (status, resp_body) = api
.post_raw("/auth/database", &body)
.unwrap_or_else(|e| e.exit());
if !status.is_success() {
// The old typed `api.post` routed non-success through `fail_response`,
// which upgrades a masked 401/403/404 into the re-auth hint. Reproduce
// that via the seam's auth-aware exit.
crate::sdk::ApiError::Status {
status,
body: resp_body,
}
.exit();
}
match serde_json::from_str(&resp_body) {
Ok(v) => v,
Err(e) => {
eprintln!("error parsing response: {e}");
std::process::exit(1);
}
}
}
/// Run a command with a database-scoped token. Creates a new database
/// first when `database` is None, then mints a JWT and execs the
/// command with it injected as HOTDATA_DATABASE_TOKEN.
pub fn run(
database: Option<&str>,
workspace_id: &str,
name: Option<&str>,
schema: &str,
tables: &[String],
expires_at: Option<&str>,
cmd: &[String],
) {
use crossterm::style::Stylize;
use std::time::{SystemTime, UNIX_EPOCH};
let api = Api::new(Some(workspace_id));
// Unlike `create`, we don't persist the auto-created database as the
// workspace's "current" database: a `run` database is scratch/ephemeral
// for the child process, addressed only by the token we mint below.
let database_id = match database {
Some(id) => id.to_string(),
None => create_and_return_id(&api, name, schema, tables, expires_at),
};
let resp = mint_database_token(&api, &database_id);
let db_id = resp.database_id.clone();
let db_jwt = resp.token.clone();
let db_refresh = resp.refresh_token.clone();
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0);
let session = crate::database_session::DatabaseSession {
access_token: db_jwt.clone(),
refresh_token: db_refresh.clone(),
database_id: db_id.clone(),
workspace_id: workspace_id.to_string(),
access_expires_at: now + resp.expires_in,
refresh_expires_at: now + resp.refresh_expires_in,
};
if let Err(e) = crate::database_session::save(&session) {
eprintln!("warning: could not persist database session: {e}");
}
eprintln!("{} {}", "database:".dark_grey(), db_id);
eprintln!("{} {}", "workspace:".dark_grey(), workspace_id);
let status = std::process::Command::new(&cmd[0])
.args(&cmd[1..])
.env("HOTDATA_DATABASE", &db_id)
.env("HOTDATA_WORKSPACE", workspace_id)
.env("HOTDATA_API_URL", &api.api_url)
.env("HOTDATA_DATABASE_TOKEN", &db_jwt)
.env("HOTDATA_DATABASE_REFRESH_TOKEN", &db_refresh)
.status();
match status {
Ok(s) => std::process::exit(s.code().unwrap_or(1)),
Err(e) => {
eprintln!("error: failed to execute '{}': {e}", cmd[0]);
std::process::exit(1);
}
}
}
pub fn create(
workspace_id: &str,
name: Option<&str>,
catalog: Option<&str>,
schema: &str,
tables: &[String],
expires_at: Option<&str>,
format: &str,
) {
use crossterm::style::Stylize;
let request = create_database_typed_request(name, catalog, schema, tables, expires_at);
let api = Api::new(Some(workspace_id));
let spinner = (format == "table").then(|| crate::util::spinner("Creating database..."));
let resp = block(api.client().databases().create(request)).unwrap_or_else(|e| {
if let Some(s) = &spinner {
s.finish_and_clear();
}
e.exit()
});
if let Some(s) = &spinner {
s.finish_and_clear();
}
let result = CreateDatabaseResponse {
id: resp.id,
name: resp.name.flatten(),
default_catalog: Some(resp.default_catalog),
default_connection_id: resp.default_connection_id,
expires_at: resp.expires_at.flatten(),
};
if let Err(e) = crate::config::save_current_database("default", workspace_id, &result.id) {
use crossterm::style::Stylize;
eprintln!(
"{}",
format!("warning: database created but could not set as current: {e}").yellow()
);
}
match format {
"json" => println!("{}", serde_json::to_string_pretty(&result).unwrap()),
"yaml" => print!("{}", serde_yaml::to_string(&result).unwrap()),
"table" => {
println!("{}", "Database created".green());
if let Some(n) = &result.name {
println!("name: {}", n.clone().cyan());
}
if let Some(c) = &result.default_catalog {
println!("catalog: {}", c.clone().cyan());
}
println!("id: {}", result.id);
if let Some(exp) = &result.expires_at {
println!("expires_at: {exp}");
}
println!();
let catalog = result
.default_catalog
.as_deref()
.or(result.name.as_deref())
.unwrap_or("default");
println!(
"{}",
format!(
concat!(
"Load a table:\n",
" hotdata databases load --catalog {0} --table <table> --file <path.parquet>\n",
" hotdata databases load --catalog {0} --table <table> --url <url>\n",
"\nQuery with:\n",
" hotdata query \"SELECT * FROM {0}.public.<table> LIMIT 10\"\n",
"\n Tip: column names are case-sensitive — wrap uppercase names in double quotes",
),
catalog
)
.dark_grey()
);
}
_ => unreachable!(),
}
}
pub fn unset(workspace_id: &str) {
use crossterm::style::Stylize;
if let Err(e) = crate::config::clear_current_database("default", workspace_id) {
eprintln!("{}", format!("error clearing current database: {e}").red());
std::process::exit(1);
}
println!("{}", "Current database cleared.".green());
}
pub fn set(workspace_id: &str, id: &str) {
use crossterm::style::Stylize;
let api = Api::new(Some(workspace_id));
if none_if_404(get_database(&api, id))
.unwrap_or_else(|e| e.exit())
.is_none()
{
eprintln!("{}", format!("error: no database with id '{id}'").red());
std::process::exit(1);
}
if let Err(e) = crate::config::save_current_database("default", workspace_id, id) {
eprintln!("{}", format!("error saving current database: {e}").red());
std::process::exit(1);
}
println!("{}", format!("Current database set to {id}").green());
}
fn resolve_current_database(provided: Option<&str>, workspace_id: &str) -> String {
if let Some(id) = provided {
return id.to_string();
}
match crate::config::load_current_database("default", workspace_id) {
Some(id) => id,
None => {
use crossterm::style::Stylize;
eprintln!(
"{}",
"error: no current database set. Use 'hotdata databases set <id>' or pass a database id.".red()
);
std::process::exit(1);
}
}
}
pub fn delete(workspace_id: &str, id_or_name: &str) {
use crossterm::style::Stylize;
let api = Api::new(Some(workspace_id));
let db = resolve_database(&api, id_or_name);
block(api.client().databases().delete(&db.id)).unwrap_or_else(|e| e.exit());
// If the deleted database was the current one, clear it so subsequent
// commands don't silently send a stale X-Database-Id header.
if crate::config::load_current_database("default", workspace_id).as_deref() == Some(&db.id) {
let _ = crate::config::clear_current_database("default", workspace_id);
}
println!("{}", "Database deleted.".green());
}
pub fn tables_list(workspace_id: &str, database: Option<&str>, schema: Option<&str>, format: &str) {
let database = resolve_current_database(database, workspace_id);
let api = Api::new(Some(workspace_id));
let db = resolve_database(&api, &database);
let catalog = db
.default_catalog
.as_deref()
.or(db.name.as_deref())
.unwrap_or("default");
let tables = collect_tables(&api, &db.default_connection_id, schema);
let rows = table_rows(catalog, tables);
match format {
"json" => println!("{}", serde_json::to_string_pretty(&rows).unwrap()),
"yaml" => print!("{}", serde_yaml::to_string(&rows).unwrap()),
"table" => {
if rows.is_empty() {
use crossterm::style::Stylize;
eprintln!("{}", "No tables found.".dark_grey());
} else {
let table_rows: Vec<Vec<String>> = rows
.iter()
.map(|r| {
vec![
r.full_name.clone(),
r.synced.to_string(),
r.last_sync
.as_deref()
.map(crate::util::format_date)
.unwrap_or_else(|| "-".to_string()),
]
})
.collect();
crate::table::print(&["TABLE", "SYNCED", "LAST_SYNC"], &table_rows);
}
}
_ => unreachable!(),
}
}
pub fn tables_load(
workspace_id: &str,
database: Option<&str>,
table: &str,
schema: Option<&str>,
file: Option<&str>,
url: Option<&str>,
upload_id: Option<&str>,
) {
use crossterm::style::Stylize;
let database = resolve_current_database(database, workspace_id);
let api = Api::new(Some(workspace_id));
// Prefer the active database when its catalog or name matches the lookup key,
// avoiding ambiguity when multiple databases share the same catalog name.
let active_id = crate::config::load_current_database("default", workspace_id);
let lookup_key = match active_id.as_deref() {
Some(id) => {
if let Some(active) = none_if_404(get_database(&api, id)).unwrap_or_else(|e| e.exit()) {
if active.default_catalog.as_deref() == Some(database.as_str())
|| active.name.as_deref() == Some(database.as_str())
{
id.to_string()
} else {
database.clone()
}
} else {
database.clone()
}
}
None => database.clone(),
};
let db = resolve_database(&api, &lookup_key);
let schema = schema_name(schema);
// clap enforces mutual exclusion; only one of these is ever Some.
let upload_id = match (upload_id, file, url) {
(Some(id), None, None) => id.to_string(),
(None, Some(path), None) => upload_parquet_file(&api, path),
(None, None, Some(u)) => upload_parquet_url(&api, u),
(None, None, None) => {
eprintln!("error: --file <path>, --url <url>, or --upload-id <id> is required");
std::process::exit(1);
}
_ => unreachable!(),
};
let path = managed_table_load_path(&db.default_connection_id, schema, table);
let body = load_table_request(&upload_id);
let spinner = crate::util::spinner("Loading table...");
let (status, resp_body) = api.post_raw(&path, &body).unwrap_or_else(|e| {
spinner.finish_and_clear();
e.exit()
});
spinner.finish_and_clear();
let (status, resp_body) = if !status.is_success()
&& crate::util::api_error(resp_body.clone()).contains("not declared")
{
// The table wasn't declared at create time. Collect existing tables so
// they are re-declared in the replacement database, then delete and
// recreate with all tables (including the new one) declared.
let existing = collect_tables(&api, &db.default_connection_id, None);
let mut all_tables: Vec<String> = existing
.iter()
.map(|t| format!("{}.{}", t.schema, t.table))
.collect();
let new_table_key = format!("{schema}.{table}");
if !all_tables.contains(&new_table_key) {
all_tables.push(new_table_key);
}
// Warn if any existing table has synced data — delete+recreate will lose it.
let synced: Vec<String> = existing
.iter()
.filter(|t| t.synced)
.map(|t| format!("{}.{}", t.schema, t.table))
.collect();
if !synced.is_empty() {
use crossterm::style::Stylize;
let catalog = db
.default_catalog
.as_deref()
.or(db.name.as_deref())
.unwrap_or(&db.id);
eprintln!(
"{}",
format!(
"warning: declaring '{}' requires recreating the database '{catalog}'. \
The following tables have loaded data that will be lost:\n {}",
table,
synced.join(", ")
)
.yellow()
);
if crate::util::is_interactive() {
use std::io::Write;
eprint!("Proceed and lose this data? [y/N] ");
std::io::stderr().flush().unwrap();
let mut input = String::new();
std::io::stdin().read_line(&mut input).unwrap();
if !input.trim().eq_ignore_ascii_case("y") {
eprintln!("{}", "Aborted.".red());
std::process::exit(1);
}
} else {
eprintln!(
"{}",
"error: cannot auto-declare table in non-interactive mode — existing data would be lost. \
Declare all tables up front with 'databases create --table <name>'."
.red()
);
std::process::exit(1);
}
}
let (del_status, del_body) = api
.delete_raw(&format!("/databases/{}", db.id))
.unwrap_or_else(|e| e.exit());
if !del_status.is_success() {
eprintln!("{}", crate::util::api_error(del_body).red());
std::process::exit(1);
}
let create_body = create_database_request(
db.name.as_deref(),
db.default_catalog.as_deref(),
schema,
&all_tables,
db.expires_at.as_deref(),
);
let (create_status, create_body_resp) = api
.post_raw("/databases", &create_body)
.unwrap_or_else(|e| e.exit());
if !create_status.is_success() {
eprintln!("{}", crate::util::api_error(create_body_resp).red());
std::process::exit(1);
}
let new_db: CreateDatabaseResponse = match serde_json::from_str(&create_body_resp) {
Ok(v) => v,
Err(e) => {
eprintln!("error parsing create response: {e}");
std::process::exit(1);
}
};
let _ = crate::config::save_current_database("default", workspace_id, &new_db.id);
let new_path = managed_table_load_path(&new_db.default_connection_id, schema, table);
let spinner = crate::util::spinner("Loading table...");
let result = api.post_raw(&new_path, &body).unwrap_or_else(|e| {
spinner.finish_and_clear();
e.exit()
});