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