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
use anyhow::{anyhow, bail, Context, Result};
use aws_sdk_athena::{
    model::{
        QueryExecutionContext,
        QueryExecutionState::{self, *},
        ResultConfiguration, ResultSet,
    },
    output::GetQueryExecutionOutput,
    Client,
};
use devtimer::DevTime;
use log::{error, info};
use regex::Regex;
use std::{collections::HashMap, env, path::PathBuf};
use tokio::time::{sleep, Duration};

use crate::utils::pretty_print;

#[derive(clap::Args, Debug, Clone)]
pub struct Apply {
    /// Target path to render. If the target path is a directory,
    /// the root folder must contains the index.sql file
    pub file: PathBuf,

    /// Change the context current working dir
    #[arg(long, short)]
    pub context: Option<PathBuf>,

    /// Dry-run
    #[arg(global = true, long, short)]
    pub dry_run: Option<bool>,

    /// AWS Profile
    /// Set this option via environment variable: export AWS_PROFILE=default
    #[arg(global = true, long, short)]
    pub profile: Option<String>,

    /// AWS Region
    #[arg(global = true, long, short)]
    /// Set this option via environment variable: export AWS_DEFAULT_REGION=us-east-1
    pub region: Option<String>,

    /// AWS Athena Workgroup
    /// Set this option via environment variable: export AWS_WORKGROUP=primary
    #[arg(global = true, long, short)]
    pub workgroup: Option<String>,

    /// AWS Athena output location
    /// The location in Amazon S3 where your query results are stored
    /// such as `s3://path/to/query/bucket/`
    /// Set this option via environment variable: export AWS_OUTPUT_LOCATION=s3://bucket/
    #[arg(global = true, long, short)]
    pub output_location: Option<String>,

    /// No pretty print for SQL
    #[arg(long)]
    pub no_pretty: Option<bool>,
}

pub async fn call(args: Apply) -> Result<()> {
    let build_args = crate::build::Build {
        file: args.file.clone(),
        out: None,
        context: args.context.clone(),
        no_pretty: None,
    };

    let sql = crate::build::build(build_args)?;
    if args.no_pretty.unwrap_or_default() {
        print!("{}", sql);
    } else {
        pretty_print(sql.as_bytes());
    }

    // Set AWS_PROFILE
    if let Some(ref profile) = args.profile {
        std::env::set_var("AWS_PROFILE", profile);
    }

    // Set AWS_DEFAULT_REGION
    if let Some(ref region) = args.region {
        std::env::set_var("AWS_DEFAULT_REGION", region);
    }

    let shared_config = aws_config::load_from_env().await;
    let client = Client::new(&shared_config);

    // Healthcheck
    submit_and_wait(client.clone(), Some("SELECT 1".to_string()), args.clone()).await?;

    // Submit SQL
    let sql = sql
        .split(';')
        .into_iter()
        .map(|s| s.trim())
        .filter(|s| !s.is_empty())
        .collect::<Vec<_>>();
    info!("Submitting {} queries to Athena", sql.len());

    let mut stats: HashMap<QueryExecutionState, i32> = HashMap::new();

    // Timer
    let mut timer = DevTime::new_simple();
    timer.start();

    for s in sql {
        let state = submit_and_wait(client.clone(), Some(s.to_string()), args.clone()).await?;

        // Update stats
        stats
            .entry(state.clone())
            .and_modify(|c| *c += 1)
            .or_insert(0);
    }

    timer.stop();

    info!("");
    info!("Statistics:");
    info!("  ==> {:?}", stats);
    info!("  ==> Took: {:?} seconds", timer.time_in_secs().unwrap());

    Ok(())
}

fn get_result_configuration(args: Apply) -> ResultConfiguration {
    let output_location = args
        .output_location
        .or_else(|| env::var("AWS_OUTPUT_LOCATION").ok());

    ResultConfiguration::builder()
        .set_output_location(output_location)
        .build()
}

fn get_query_execution_context(query: Option<String>) -> Option<QueryExecutionContext> {
    query.as_ref()?;

    let database = get_database_from_sql(query.unwrap());
    database.as_ref()?;

    let ctx = QueryExecutionContext::builder()
        .set_database(database)
        .build();

    Some(ctx)
}

async fn submit_and_wait(
    client: Client,
    query: Option<String>,
    args: Apply,
) -> Result<QueryExecutionState> {
    if query.clone().is_none() {
        bail!("Empty query");
    }

    // Timer
    let mut timer = DevTime::new_simple();
    timer.start();

    let workgroup = args.workgroup.clone();
    let result_configuration = get_result_configuration(args.clone());
    let query_execution_context = get_query_execution_context(query.clone());
    let query = query.unwrap();

    match &query_execution_context {
        Some(ctx) => match ctx.database() {
            Some(database) => info!("\nSubmitting to database `{}`: ", database),
            _ => info!("\nSubmitting ..."),
        },
        _ => info!("\nSubmitting ..."),
    }

    if args.no_pretty.unwrap_or_default() {
        print!("{}", query);
    } else {
        pretty_print(query.as_bytes());
    }

    let resp = client
        .start_query_execution()
        .set_query_string(Some(query))
        .set_work_group(workgroup)
        .set_result_configuration(Some(result_configuration.clone()))
        .set_query_execution_context(query_execution_context)
        .send()
        .await?;

    let query_execution_id = resp.query_execution_id().unwrap_or_default();
    info!("Query execution id: {}", &query_execution_id);

    let mut state: QueryExecutionState;

    loop {
        let resp = client
            .get_query_execution()
            .set_query_execution_id(Some(query_execution_id.to_string()))
            .send()
            .await?;

        state = status(&resp).expect("could not get query status").clone();

        match state {
            Queued | Running => {
                sleep(Duration::from_secs(5)).await;
                info!("State: {:?}, sleep 5 secs ...", state);
            }
            Cancelled | Failed => {
                error!("State: {:?}", state);

                match get_query_result(&client, query_execution_id.to_string()).await {
                    Ok(result) => info!("Result: {:?}", result),
                    Err(e) => error!("Result error: {:?}", e),
                }

                break;
            }
            _ => {
                let millis = total_execution_time(&resp).unwrap();
                info!("State: {:?}", state);
                info!("Total execution time: {} millis", millis);

                match get_query_result(&client, query_execution_id.to_string()).await {
                    Ok(result) => info!("Result: {:?}", result),
                    Err(e) => error!("Result error: {:?}", e),
                }

                break;
            }
        }
    }

    timer.stop();
    info!("Took: {} secs", timer.time_in_secs().unwrap());

    Ok(state.clone())
}

fn status(resp: &GetQueryExecutionOutput) -> Option<&QueryExecutionState> {
    resp.query_execution().unwrap().status().unwrap().state()
}

fn total_execution_time(resp: &GetQueryExecutionOutput) -> Option<i64> {
    resp.query_execution()
        .unwrap()
        .statistics()
        .unwrap()
        .total_execution_time_in_millis()
}

async fn get_query_result(client: &Client, query_execution_id: String) -> Result<ResultSet> {
    let resp = client
        .get_query_results()
        .set_query_execution_id(Some(query_execution_id.clone()))
        .send()
        .await
        .with_context(|| {
            format!(
                "could not get query results for query id {}",
                query_execution_id
            )
        })?;

    Ok(resp
        .result_set()
        .ok_or_else(|| anyhow!("could not get query result"))?
        .clone())
}

fn get_database_from_sql<S: AsRef<str>>(sql: S) -> Option<String> {
    let re = vec![
        Regex::new(r"(?i)--\s+Database:\s(.*)").unwrap(),
        Regex::new(r"(?i)/*\s+Database:\s([^\s]+)\s\*/").unwrap(),
    ];

    for r in re.iter() {
        if let Some(caps) = r.captures(sql.as_ref()) {
            let name = caps.get(1).map_or("", |m| m.as_str());
            return Some(name.trim().to_string());
        }
    }

    None
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_get_database_from_sql() {
        let sql = "-- database: db0";
        assert_eq!(get_database_from_sql(sql).unwrap(), "db0");

        let sql = "-- database: db1\nSELECT * FROM ...;";
        assert_eq!(get_database_from_sql(sql).unwrap(), "db1");

        let sql = "-- Database: db2\nSELECT * FROM ...;";
        assert_eq!(get_database_from_sql(sql).unwrap(), "db2");

        let sql = "-- Database: db3 \nSELECT * FROM ...;";
        assert_eq!(get_database_from_sql(sql).unwrap(), "db3");

        let sql = "-- Database: db4    \nSELECT * FROM ...;";
        assert_eq!(get_database_from_sql(sql).unwrap(), "db4");

        let sql = "--   Database: db4    \nSELECT * FROM ...;";
        assert_eq!(get_database_from_sql(sql).unwrap(), "db4");

        let sql = "/* Database: db5 */\nSELECT * FROM ...;";
        assert_eq!(get_database_from_sql(sql).unwrap(), "db5");

        let sql = "/* database: db6 */\nSELECT * FROM ...;";
        assert_eq!(get_database_from_sql(sql).unwrap(), "db6");

        let sql = "/*        database: db7 */\nSELECT * FROM ...;";
        assert_eq!(get_database_from_sql(sql).unwrap(), "db7");

        let sql = "SELECT * FROM ...;";
        assert!(get_database_from_sql(sql).is_none());

        let sql = "-- database: db0 \n-- database: db1";
        assert_eq!(get_database_from_sql(sql).unwrap(), "db0");

        let sql = "/* database: db0 */\n/* database: db1 */";
        assert_eq!(get_database_from_sql(sql).unwrap(), "db0");
    }

    #[test]
    fn test_get_database_from_sql_with_comment() {
        let sql = "-- database: db0\n-- comment\nSELECT * FROM ...;";
        assert_eq!(get_database_from_sql(sql).unwrap(), "db0");

        let sql = "-- database: db0\n-- comment\n-- comment\nSELECT * FROM ...;";
        assert_eq!(get_database_from_sql(sql).unwrap(), "db0");

        let sql = "-- database: db0\n-- comment\n-- comment\n-- comment\nSELECT * FROM ...;";
        assert_eq!(get_database_from_sql(sql).unwrap(), "db0");
    }
}