sql_cli/config/
schema_config.rs

1use serde::{Deserialize, Serialize};
2use std::fs;
3use std::path::Path;
4
5#[derive(Debug, Clone, Serialize, Deserialize)]
6pub struct SchemaConfig {
7    pub tables: Vec<TableConfig>,
8}
9
10#[derive(Debug, Clone, Serialize, Deserialize)]
11pub struct TableConfig {
12    pub name: String,
13    pub columns: Vec<String>,
14}
15
16// Load schema from a JSON file if it exists, otherwise use defaults
17pub fn load_schema_config() -> SchemaConfig {
18    // Check for schema.json in current directory or config directory
19    let mut paths = vec![
20        String::from("schema.json"),
21        String::from(".sql-cli/schema.json"),
22    ];
23
24    // Add config directory path if available
25    if let Some(config_dir) = dirs::config_dir() {
26        if let Some(path_str) = config_dir.join("sql-cli/schema.json").to_str() {
27            paths.push(String::from(path_str));
28        }
29    }
30
31    for path in paths {
32        if Path::new(&path).exists() {
33            if let Ok(contents) = fs::read_to_string(&path) {
34                if let Ok(config) = serde_json::from_str::<SchemaConfig>(&contents) {
35                    eprintln!("Loaded schema from: {}", path);
36                    return config;
37                }
38            }
39        }
40    }
41
42    // Return default schema
43    SchemaConfig {
44        tables: vec![
45            TableConfig {
46                name: String::from("trade_deal"),
47                columns: get_full_trade_deal_columns(),
48            },
49            TableConfig {
50                name: String::from("instrument"),
51                columns: vec![
52                    String::from("instrumentId"),
53                    String::from("name"),
54                    String::from("type"),
55                ],
56            },
57        ],
58    }
59}
60
61// Example configuration for full schema with 190+ columns
62// This can be loaded from JSON/YAML or your REST API
63
64pub fn get_full_trade_deal_columns() -> Vec<String> {
65    vec![
66        // Trade identifiers
67        "dealId",
68        "platformOrderId",
69        "externalOrderId",
70        "parentOrderId",
71        // Dates
72        "tradeDate",
73        "settlementDate",
74        "valueDate",
75        "maturityDate",
76        "lastModifiedDate",
77        "createdDate",
78        "confirmationDate",
79        "executionDate",
80        // Instrument details
81        "instrumentId",
82        "instrumentName",
83        "instrumentType",
84        "isin",
85        "cusip",
86        "sedol",
87        "ticker",
88        "exchange",
89        // Quantities and prices
90        "quantity",
91        "price",
92        "notional",
93        "settlementAmount",
94        "grossAmount",
95        "netAmount",
96        "accruedInterest",
97        "accrual",
98        "commission",
99        "fees",
100        "tax",
101        "spread",
102        "currency",
103        "baseCurrency",
104        "quoteCurrency",
105        "settlementCurrency",
106        // Counterparty info
107        "counterparty",
108        "counterpartyId",
109        "counterpartyType",
110        "counterpartyCountry",
111        "counterpartyLei",
112        // Internal info
113        "trader",
114        "traderId",
115        "book",
116        "bookId",
117        "portfolio",
118        "portfolioId",
119        "strategy",
120        "desk",
121        "legalEntity",
122        "branch",
123        "region",
124        "side",
125        "productType",
126        "instrumentClass",
127        "assetClass",
128        // Trading venue and clearing
129        "venue",
130        "executionVenue",
131        "clearingHouse",
132        "clearingBroker",
133        "prime",
134        "custodian",
135        "subCustodian",
136        // Status and workflow
137        "status",
138        "confirmationStatus",
139        "settlementStatus",
140        "allocationStatus",
141        "clearingStatus",
142        "bookingStatus",
143        // Risk metrics
144        "pv01",
145        "dv01",
146        "delta",
147        "gamma",
148        "vega",
149        "theta",
150        "duration",
151        "convexity",
152        "yield",
153        "spread",
154        // Compliance
155        "regulatoryReporting",
156        "mifidClassification",
157        "bestExecution",
158        "preTradeTransparency",
159        "postTradeTransparency",
160        // Comments and metadata
161        "comments",
162        "notes",
163        "auditTrail",
164        "version",
165        "source",
166        "sourceSystem",
167        "lastUpdatedBy",
168        "createdBy",
169        // Additional reference fields
170        "clientOrderId",
171        "brokerOrderId",
172        "exchangeOrderId",
173        "blockTradeId",
174        "allocationId",
175        "confirmationId",
176        // Add more columns as needed...
177    ]
178    .into_iter()
179    .map(String::from)
180    .collect()
181}
182
183// Function to save the current schema to a file (useful for generating examples)
184pub fn save_schema_example(path: &str) -> Result<(), Box<dyn std::error::Error>> {
185    let schema = load_schema_config();
186    let json = serde_json::to_string_pretty(&schema)?;
187    fs::write(path, json)?;
188    Ok(())
189}
190
191// Example of LINQ-style operators that could be supported
192pub enum LinqOperator {
193    Contains(String),        // field.Contains('value')
194    StartsWith(String),      // field.StartsWith('value')
195    EndsWith(String),        // field.EndsWith('value')
196    GreaterThan(String),     // field > value
197    LessThan(String),        // field < value
198    Between(String, String), // field >= value1 && field <= value2
199    In(Vec<String>),         // field in (value1, value2, ...)
200    IsNull,                  // field == null
201    IsNotNull,               // field != null
202}
203
204// Date constructor support
205pub enum DateConstructor {
206    Today,               // DateTime.Today
207    Now,                 // DateTime.Now
208    Date(i32, u32, u32), // DateTime(2024, 1, 15)
209    DateOffset(i32),     // DateTime.Today.AddDays(-7)
210}