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
//! This crate provides Turbosql's procedural macros.
//!
//! Please refer to the `turbosql` crate for how to set this up.

#![forbid(unsafe_code)]

// #![allow(unused_imports)]
const SQLITE_U64_ERROR: &str = r##"SQLite cannot natively store unsigned 64-bit integers, so Turbosql does not support u64 fields. Use i64, u32, f64, or a string or binary format instead. (see https://github.com/trevyn/turbosql/issues/3 )"##;

use once_cell::sync::Lazy;
use proc_macro2::Span;
use proc_macro_error::{abort, abort_call_site, proc_macro_error};
use quote::{format_ident, quote, ToTokens};
use rusqlite::{params, Connection, Statement};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::sync::Mutex;
use syn::parse::{Parse, ParseStream};
use syn::punctuated::Punctuated;
use syn::spanned::Spanned;
use syn::{
 parse_macro_input, Data, DeriveInput, Expr, Fields, FieldsNamed, Ident, LitStr, Meta, NestedMeta,
 Token, Type,
};

#[cfg(not(feature = "test"))]
const MIGRATIONS_FILENAME: &str = "migrations.toml";
#[cfg(feature = "test")]
const MIGRATIONS_FILENAME: &str = "test.migrations.toml";

mod insert;
mod update;

// trait Ok<T> {
//  fn ok(self) -> Result<T, anyhow::Error>;
// }

// impl<T> Ok<T> for Option<T> {
//  fn ok(self) -> Result<T, anyhow::Error> {
//   self.ok_or_else(|| anyhow::anyhow!("NoneError"))
//  }
// }

#[derive(Debug, Clone)]
struct Table {
 ident: Ident,
 span: Span,
 name: String,
 columns: Vec<Column>,
}

#[derive(Clone, Serialize, Deserialize, Debug)]
struct MiniTable {
 name: String,
 columns: Vec<MiniColumn>,
}

impl ToTokens for Table {
 fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
  let ident = &self.ident;
  tokens.extend(quote!(#ident));
 }
}

#[derive(Debug, Clone)]
struct Column {
 ident: Ident,
 span: Span,
 name: String,
 rust_type: String,
 sql_type: &'static str,
}

#[derive(Clone, Serialize, Deserialize, Debug)]
struct MiniColumn {
 name: String,
 rust_type: String,
 sql_type: String,
}

// static TEST_DB: Lazy<Mutex<Connection>> =
//  Lazy::new(|| Mutex::new(Connection::open_in_memory().unwrap()));

static LAST_TABLE_NAME: Lazy<Mutex<String>> = Lazy::new(|| Mutex::new("none".to_string()));

static TABLES: Lazy<Mutex<BTreeMap<String, MiniTable>>> = Lazy::new(|| Mutex::new(BTreeMap::new()));

// #[proc_macro]
// pub fn set_db_path(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
//  let input = proc_macro2::TokenStream::from(input);

//  eprintln!("IN SET DB PATH!");
//  eprintln!("{:#?}", input);

//  let mut db_path = DB_PATH.lock().unwrap();

//  let mut iter = input.into_iter();

//  *db_path = match iter.next() {
//   Some(proc_macro2::TokenTree::Literal(literal)) => literal.to_string(),
//   _ => panic!("Expected string literal"),
//  };

//  proc_macro::TokenStream::new()
// }

#[derive(Debug)]
struct SelectTokens {
 tokens: proc_macro2::TokenStream,
}

#[derive(Debug)]
struct ExecuteTokens {
 tokens: proc_macro2::TokenStream,
}

#[derive(Debug)]
struct QueryParams {
 params: Punctuated<Expr, Token![,]>,
}

impl Parse for QueryParams {
 fn parse(input: ParseStream) -> syn::Result<Self> {
  Ok(QueryParams {
   params: if input.peek(Token![,]) {
    input.parse::<Token![,]>().unwrap();
    input.parse_terminated(Expr::parse)?
   } else {
    Punctuated::new()
   },
  })
 }
}

#[derive(Clone, Debug)]
struct ResultType {
 container: Option<Ident>,
 contents: Option<Ident>,
}

// impl Parse for ResultType {
//  fn parse(input: ParseStream) -> syn::Result<Self> {
//   let path = input.parse::<syn::Path>();
//   eprintln!("{:#?}", path);
//   Ok(ResultType {})
//  }
// }

#[derive(Debug)]
struct MembersAndCasters {
 members: Vec<(Ident, Ident, usize)>,
 struct_members: Vec<proc_macro2::TokenStream>,
 row_casters: Vec<proc_macro2::TokenStream>,
}

impl MembersAndCasters {
 fn create(members: Vec<(Ident, Ident, usize)>) -> MembersAndCasters {
  let struct_members: Vec<_> = members.iter().map(|(name, ty, _i)| quote!(#name: #ty)).collect();
  let row_casters =
   members.iter().map(|(name, _ty, i)| quote!(#name: row.get(#i)?)).collect::<Vec<_>>();

  Self { members, struct_members, row_casters }
 }
}

fn _extract_explicit_members(columns: &[String]) -> Option<MembersAndCasters> {
 // let members: Vec<_> = columns
 //  .iter()
 //  .enumerate()
 //  .filter_map(|(i, cap)| {
 //   let col_name = cap;
 //   let mut parts: Vec<_> = col_name.split('_').collect();
 //   if parts.len() < 2 {
 //    return None;
 //   }
 //   let ty = parts.pop()?;
 //   let name = parts.join("_");
 //   Some((format_ident!("{}", name), format_ident!("{}", ty), i))
 //  })
 //  .collect();

 println!("extractexplicitmembers: {:#?}", columns);

 // MembersAndCasters::create(members);
 // syn::parse_str::<Ident>

 None
}

fn _extract_stmt_members(stmt: &Statement, span: &Span) -> MembersAndCasters {
 let members: Vec<_> = stmt
  .column_names()
  .iter()
  .enumerate()
  .map(|(i, col_name)| {
   let mut parts: Vec<_> = col_name.split('_').collect();

   if parts.len() < 2 {
    abort!(
     span,
     "SQL column name {:#?} must include a type annotation, e.g. {}_String or {}_i64.",
     col_name,
     col_name,
     col_name
    )
   }

   let ty = parts.pop().unwrap();

   match ty {
    "i64" | "String" => (),
    _ => abort!(span, "Invalid type annotation \"_{}\", try e.g. _String or _i64.", ty),
   }

   let name = parts.join("_");

   (format_ident!("{}", name), format_ident!("{}", ty), i)
  })
  .collect();

 // let struct_members: Vec<_> = members.iter().map(|(name, ty, _i)| quote!(#name: #ty)).collect();
 // let row_casters: Vec<_> =
 //  members.iter().map(|(name, _ty, i)| quote!(#name: row.get(#i).unwrap())).collect();

 MembersAndCasters::create(members)
}

enum ParseStatementType {
 Execute,
 Select,
}
use ParseStatementType::{Execute, Select};

#[derive(Debug)]
struct StatementInfo {
 parameter_count: usize,
 column_names: Vec<String>,
}

impl StatementInfo {
 fn membersandcasters(&self) -> syn::parse::Result<MembersAndCasters> {
  Ok(MembersAndCasters::create(
   self
    .column_names
    .iter()
    .enumerate()
    .map(|(i, col_name)| Ok((syn::parse_str::<Ident>(col_name)?, format_ident!("None"), i)))
    .collect::<syn::parse::Result<Vec<_>>>()?,
  ))
 }
}

#[derive(Clone, Debug, Serialize, Deserialize, Default)]
struct MigrationsToml {
 migrations_append_only: Option<Vec<String>>,
 output_generated_schema_for_your_information_do_not_edit: Option<String>,
 output_generated_tables_do_not_edit: Option<BTreeMap<String, MiniTable>>,
}

fn migrations_to_tempdb(migrations: &[String]) -> Connection {
 let tempdb = rusqlite::Connection::open_in_memory().unwrap();

 tempdb
  .execute_batch(
   "CREATE TABLE _turbosql_migrations (rowid INTEGER PRIMARY KEY, migration TEXT NOT NULL);",
  )
  .unwrap();

 migrations.iter().filter(|m| !m.starts_with("--")).for_each(|m| {
  match tempdb.execute(m, params![]) {
   Ok(_) => (),
   Err(rusqlite::Error::ExecuteReturnedResults) => (), // pragmas
   Err(e) => abort_call_site!("Running migrations on temp db: {:?} {:?}", m, e),
  }
 });

 tempdb
}

fn migrations_to_schema(migrations: &[String]) -> Result<String, rusqlite::Error> {
 Ok(
  migrations_to_tempdb(migrations)
   .prepare("SELECT sql FROM sqlite_master WHERE type='table' ORDER BY sql")?
   .query_map(params![], |row| Ok(row.get(0)?))?
   .collect::<Result<Vec<String>, _>>()?
   .join("\n"),
 )
}

fn read_migrations_toml() -> MigrationsToml {
 let lockfile = std::fs::File::create(std::env::temp_dir().join("migrations.toml.lock")).unwrap();
 fs2::FileExt::lock_exclusive(&lockfile).unwrap();

 let migrations_toml_path = std::env::current_dir().unwrap().join(MIGRATIONS_FILENAME);
 let migrations_toml_path_lossy = migrations_toml_path.to_string_lossy();

 match migrations_toml_path.exists() {
  true => {
   let toml_str = std::fs::read_to_string(&migrations_toml_path)
    .unwrap_or_else(|e| abort_call_site!("Unable to read {}: {:?}", migrations_toml_path_lossy, e));

   let toml_decoded: MigrationsToml = toml::from_str(&toml_str).unwrap_or_else(|e| {
    abort_call_site!("Unable to decode toml in {}: {:?}", migrations_toml_path_lossy, e)
   });

   toml_decoded
  }
  false => MigrationsToml::default(),
 }
}

fn validate_sql<S: AsRef<str>>(sql: S) -> Result<StatementInfo, rusqlite::Error> {
 let tempdb = migrations_to_tempdb(&read_migrations_toml().migrations_append_only.unwrap());

 let stmt = tempdb.prepare(sql.as_ref());

 // eprintln!("{:#?}", stmt);

 let stmt = stmt?;

 Ok(StatementInfo {
  parameter_count: stmt.parameter_count(),
  column_names: stmt.column_names().into_iter().map(str::to_string).collect(),
 })
}

fn validate_sql_or_abort<S: AsRef<str> + std::fmt::Debug>(sql: S) -> StatementInfo {
 validate_sql(sql.as_ref()).unwrap_or_else(|e| {
  abort_call_site!(r#"Error validating SQL statement: "{}". SQL: {:?}"#, e, sql)
 })
}

fn do_parse_tokens(
 input: ParseStream,
 statement_type: ParseStatementType,
) -> syn::Result<proc_macro2::TokenStream> {
 let span = input.span();

 // Get result type and SQL

 let result_type = input.parse::<Type>().ok();
 let sql = input.parse::<LitStr>().ok().map(|s| s.value());

 // Try validating SQL as-is

 let stmt_info = sql.clone().and_then(|s| validate_sql(s).ok());

 // Try adding SELECT if it didn't validate

 let (sql, stmt_info) = match (sql, stmt_info) {
  (Some(sql), None) => {
   let sql_with_select = format!("SELECT {}", sql);
   let stmt_info = validate_sql(&sql_with_select).ok();
   (Some(if stmt_info.is_some() { sql_with_select } else { sql }), stmt_info)
  }
  t => t,
 };

 // eprintln!("{:?}, {:?}, {:?}", quote!(#result_type).to_string(), sql, stmt_info);

 // Extract container type (e.g. Vec, Option) if present

 let result_type = match result_type {
  Some(syn::Type::Path(syn::TypePath { path: syn::Path { segments, .. }, .. }))
   if segments.len() == 1 =>
  {
   let segment = segments.first().unwrap();
   Some(match segment.ident.to_string().as_str() {
    "Vec" | "Option" => match &segment.arguments {
     syn::PathArguments::AngleBracketed(syn::AngleBracketedGenericArguments { args, .. })
      if args.len() == 1 =>
     {
      let arg = args.first().unwrap();
      match arg {
       syn::GenericArgument::Type(syn::Type::Path(syn::TypePath {
        path: syn::Path { segments, .. },
        ..
       }))
        if segments.len() == 1 =>
       {
        let contents_segment = segments.first().unwrap();
        ResultType {
         container: Some(segment.ident.clone()),
         contents: Some(contents_segment.ident.clone()),
        }
       }
       syn::GenericArgument::Type(syn::Type::Infer(_)) => {
        ResultType { container: Some(segment.ident.clone()), contents: None }
       }
       _ => abort_call_site!("No segments found for container type {:#?}", arg),
      }
     }
     _ => abort_call_site!("No arguments found for container type"),
    },
    _ => ResultType { container: None, contents: Some(segment.ident.clone()) },
   })
  }
  Some(_) => abort_call_site!("Could not parse result_type"),
  None => None,
 };

 // eprintln!("{:?}, {:?}, {:?}", result_type, sql, stmt_info);

 // If it didn't still validate and we have a non-inferred result type, try adding SELECT ... FROM

 let (sql, stmt_info) = match (result_type.clone(), sql, stmt_info) {
  //
  // Have result type and SQL did not validate, try generating SELECT ... FROM
  (Some(ResultType { contents: Some(contents), .. }), sql, None) => {
   let result_type = contents.to_string();
   let table_name = result_type.to_lowercase();
   let tables = TABLES.lock().unwrap();
   let table = match tables.get(&table_name) {
    Some(t) => t.clone(),
    None => {
     let t = match read_migrations_toml().output_generated_tables_do_not_edit {
      Some(m) => m.get(&table_name).cloned(),
      None => None,
     };

     match t {
      Some(t) => t,
      None => {
       abort!(
        span,
        "Table {:?} not found. Does struct {} exist and have #[derive(Turbosql, Default)]?",
        table_name,
        result_type
       );
      }
     }
    }
   };

   let column_names_str =
    table.columns.iter().map(|c| c.name.as_str()).collect::<Vec<_>>().join(", ");

   let sql = format!("SELECT {} FROM {} {}", column_names_str, table_name, sql.unwrap_or_default());

   (sql.clone(), validate_sql_or_abort(sql))
  }

  // Otherwise, everything is validated, just unwrap
  (_, Some(sql), Some(stmt_info)) => (sql, stmt_info),

  _ => abort_call_site!("no predicate and no result type found"),
 };

 // eprintln!("{:?} {:?}, {:?}", &result_type, sql, stmt_info);

 // try parse sql here with nom-sql

 // eprintln!("NOM_SQL: {:#?}", nom_sql::parser::parse_query(&sql));

 // pull explicit members from statement info

 // let explicit_members = extract_explicit_members(&stmt_info.column_names);

 // get query params and validate their count against what the statement is expecting

 let QueryParams { params } = input.parse()?;

 if params.len() != stmt_info.parameter_count {
  abort!(
   span,
   "Expected {} bound parameter{}, got {}: {:?}",
   stmt_info.parameter_count,
   if stmt_info.parameter_count == 1 { "" } else { "s" },
   params.len(),
   sql
  );
 }

 if !input.is_empty() {
  return Err(input.error("Expected parameters"));
 }

 // if we return no columns, this should be an execute

 if stmt_info.column_names.is_empty() {
  if !matches!(statement_type, Execute) {
   abort_call_site!("No rows returned from SQL, use execute! instead.");
  }

  return Ok(quote! {
  {
   (|| -> ::turbosql::Result<usize> {
    ::turbosql::__TURBOSQL_DB.with(|db| {
     let db = db.borrow_mut();
     let mut stmt = db.prepare_cached(#sql)?;
     stmt.execute(::turbosql::params![#params])
    })
   })()
  }
  });
 }

 if !matches!(statement_type, Select) {
  abort_call_site!("Rows returned from SQL, use select! instead.");
 }

 // dispatch

 // let (struct_members, row_casters) = match (&result_type, &stmt_info, explicit_members) {
 //  (Some(_result_type), stmt_info, None) => {
 //   let members: Vec<_> = stmt_info
 //    .column_names
 //    .iter()
 //    .enumerate()
 //    .map(|(i, col_name)| (format_ident!("{}", col_name), format_ident!("None"), i))
 //    .collect();

 //   let m = MembersAndCasters::create(members);

 //   (m.struct_members, m.row_casters)
 //  }

 //  _ => abort!(span, "Expected explicitly typed return values or a return type."),
 // };

 // let struct_decl = None;
 // let (result_type, struct_decl) = match &result_type {
 //  Some(result_type) => (result_type, None),
 //  // Some(ResultType { contents, .. }) => (quote!(#contents), None),
 //  // Some(t) => (quote!(#t), None, Some(quote!(, ..Default::default()))),
 //  None => {
 //   let tsr = format_ident!("TurbosqlResult");
 //   (
 //    quote!(#tsr),
 //    Some(quote! {
 //     #[derive(Debug, Clone, ::turbosql::Serialize)]
 //     struct #tsr { #(#struct_members),* }
 //    }),
 //   )
 //  }
 // };

 let tokens = match result_type {
  //
  // Vec
  Some(ResultType { container: Some(container), contents: Some(contents) })
   if container == "Vec" =>
  {
   let m = stmt_info
    .membersandcasters()
    .unwrap_or_else(|_| abort_call_site!("stmt_info.membersandcasters failed"));
   let row_casters = m.row_casters;

   quote! {
    {
     // #struct_decl
     (|| -> ::turbosql::Result<Vec<#contents>> {
      ::turbosql::__TURBOSQL_DB.with(|db| {
       let db = db.borrow_mut();
       let mut stmt = db.prepare_cached(#sql)?;
       let result = stmt.query_map(::turbosql::params![#params], |row| {
        Ok(#contents {
         #(#row_casters),*
         // #default
        })
       })?.collect::<Vec<_>>();

       let result = result.into_iter().flatten().collect::<Vec<_>>();

       Ok(result)
      })
     })()
    }
   }
  }

  // Option
  Some(ResultType { container: Some(container), contents: Some(contents) })
   if container == "Option" =>
  {
   let m = stmt_info
    .membersandcasters()
    .unwrap_or_else(|_| abort_call_site!("stmt_info.membersandcasters failed"));
   let row_casters = m.row_casters;

   quote! {
    {
     // #struct_decl
     (|| -> ::turbosql::Result<Option<#contents>> {
      use ::turbosql::OptionalExtension;
      ::turbosql::__TURBOSQL_DB.with(|db| {
       let db = db.borrow_mut();
       let mut stmt = db.prepare_cached(#sql)?;
       let result = stmt.query_row(::turbosql::params![#params], |row| -> ::turbosql::Result<#contents> {
        Ok(#contents {
         #(#row_casters),*
         // #default
        })
       }).optional()?;

       Ok(result)
      })
     })()
    }
   }
  }

  // Primitive type
  Some(ResultType { container: None, contents: Some(contents) })
   if ["f32", "f64", "i8", "u8", "i16", "u16", "i32", "u32", "i64", "String", "bool"]
    .contains(&&contents.to_string().as_str()) =>
  {
   quote! {
    {
     (|| -> ::turbosql::Result<#contents> {
      ::turbosql::__TURBOSQL_DB.with(|db| {
       let db = db.borrow_mut();
       let mut stmt = db.prepare_cached(#sql)?;
       let result = stmt.query_row(::turbosql::params![#params], |row| -> ::turbosql::Result<#contents> {
        Ok(row.get(0)?)
       })?;
       Ok(result)
      })
     })()
    }
   }
  }

  // Custom struct type
  Some(ResultType { container: None, contents: Some(contents) }) => {
   let m = stmt_info
    .membersandcasters()
    .unwrap_or_else(|_| abort_call_site!("stmt_info.membersandcasters failed"));
   let row_casters = m.row_casters;

   quote! {
    {
     (|| -> ::turbosql::Result<#contents> {
      ::turbosql::__TURBOSQL_DB.with(|db| {
       let db = db.borrow_mut();
       let mut stmt = db.prepare_cached(#sql)?;
       let result = stmt.query_row(::turbosql::params![#params], |row| -> ::turbosql::Result<#contents> {
        Ok(#contents {
         #(#row_casters),*
         // #default
        })
       })?;
       Ok(result)
      })
     })()
    }
   }
  }

  // Inferred
  Some(ResultType { container: Some(_container), contents: None }) => abort_call_site!("INFERRED"),
  _ => abort_call_site!("unknown result_type"),
 };

 Ok(tokens)
}

impl Parse for SelectTokens {
 fn parse(input: ParseStream) -> syn::Result<Self> {
  Ok(SelectTokens { tokens: do_parse_tokens(input, Select)? })
 }
}

impl Parse for ExecuteTokens {
 fn parse(input: ParseStream) -> syn::Result<Self> {
  Ok(ExecuteTokens { tokens: do_parse_tokens(input, Execute)? })
 }
}

/// Executes a SQL statement. On success, returns the number of rows that were changed or inserted or deleted.
#[proc_macro]
#[proc_macro_error]
pub fn execute(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
 let ExecuteTokens { tokens } = parse_macro_input!(input);
 proc_macro::TokenStream::from(tokens)
}

/// Executes a SQL SELECT statement with optionally automatic `SELECT` and `FROM` clauses.
#[proc_macro]
#[proc_macro_error]
pub fn select(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
 let SelectTokens { tokens } = parse_macro_input!(input);
 proc_macro::TokenStream::from(tokens)
}

/// Derive this on a `struct` to create a corresponding SQLite table and `Turbosql` trait methods.
#[proc_macro_derive(Turbosql, attributes(turbosql))]
#[proc_macro_error]
pub fn turbosql_derive_macro(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
 // parse tokenstream and set up table struct

 let input = parse_macro_input!(input as DeriveInput);
 let table_span = input.span();
 let table_ident = input.ident;
 let table_name = table_ident.to_string().to_lowercase();

 let ltn = LAST_TABLE_NAME.lock().unwrap().clone();

 let mut last_table_name_ref = LAST_TABLE_NAME.lock().unwrap();
 *last_table_name_ref = format!("{}, {}", ltn, table_name);

 let fields = match input.data {
  Data::Struct(ref data) => match data.fields {
   Fields::Named(ref fields) => fields,
   Fields::Unnamed(_) | Fields::Unit => unimplemented!(),
  },
  Data::Enum(_) | Data::Union(_) => unimplemented!(),
 };

 let table = Table {
  ident: table_ident,
  span: table_span,
  name: table_name.clone(),
  columns: extract_columns(fields),
 };

 let minitable = MiniTable {
  name: table_name.clone(),
  columns: table
   .columns
   .iter()
   .map(|c| MiniColumn {
    name: c.name.clone(),
    sql_type: c.sql_type.to_string(),
    rust_type: c.rust_type.clone(),
   })
   .collect(),
 };

 TABLES.lock().unwrap().insert(table_name, minitable);
 create(&table);

 // create trait functions

 let fn_insert = insert::insert(&table);
 let fn_update = update::update(&table);

 // output tokenstream

 proc_macro::TokenStream::from(quote! {
  impl #table {
   #fn_insert
   #fn_update
  }
 })
}

/// Convert syn::FieldsNamed to our Column type.
fn extract_columns(fields: &FieldsNamed) -> Vec<Column> {
 let columns = fields
  .named
  .iter()
  .filter_map(|f| {
   // Skip (skip) fields

   for attr in &f.attrs {
    let meta = attr.parse_meta().unwrap();
    match meta {
     Meta::List(list) if list.path.is_ident("turbosql") => {
      for value in list.nested.iter() {
       if let NestedMeta::Meta(meta) = value {
        match meta {
         Meta::Path(p) if p.is_ident("skip") => {
          // TODO: For skipped fields, Handle derive(Default) requirement better
          // require Option and manifest None values
          return None;
         }
         _ => (),
        }
       }
      }
     }
     _ => (),
    }
   }

   let ident = &f.ident;
   let name = ident.as_ref().unwrap().to_string();

   let ty = &f.ty;
   let ty_str = quote!(#ty).to_string();

   // TODO: have specific error messages or advice for other numeric types
   // specifically, sqlite cannot represent u64 integers, would be coerced to float.
   // https://sqlite.org/fileformat.html

   let sql_type = match (name.as_str(), ty_str.as_str()) {
    ("rowid", "Option < i64 >") => "INTEGER PRIMARY KEY",
    ("rowid", "Option < i54 >") => "INTEGER PRIMARY KEY",
    // (_, "i64") => "INTEGER NOT NULL",
    (_, "Option < i8 >") => "INTEGER",
    (_, "Option < u8 >") => "INTEGER",
    (_, "Option < i16 >") => "INTEGER",
    (_, "Option < u16 >") => "INTEGER",
    (_, "Option < i32 >") => "INTEGER",
    (_, "Option < u32 >") => "INTEGER",
    (_, "Option < i54 >") => "INTEGER",
    (_, "Option < i64 >") => "INTEGER",
    (_, "u64") => abort!(ty, SQLITE_U64_ERROR),
    (_, "Option < u64 >") => abort!(ty, SQLITE_U64_ERROR),
    // (_, "f64") => "REAL NOT NULL",
    (_, "Option < f64 >") => "REAL",
    (_, "Option < f32 >") => "REAL",
    // (_, "bool") => "BOOLEAN NOT NULL",
    (_, "Option < bool >") => "BOOLEAN",
    // (_, "String") => "TEXT NOT NULL",
    (_, "Option < String >") => "TEXT",
    // SELECT LENGTH(blob_column) ... will be null if blob is null
    // (_, "Blob") => "BLOB NOT NULL",
    (_, "Option < Blob >") => "BLOB",
    _ => abort!(ty, "turbosql doesn't support rust type: {}", ty_str),
   };

   Some(Column {
    ident: ident.clone().unwrap(),
    span: ty.span(),
    rust_type: ty_str,
    name,
    sql_type,
   })
  })
  .collect::<Vec<_>>();

 // Make sure we have a rowid column, to keep a persistent rowid for blob access.
 // see https://www.sqlite.org/rowidtable.html :
 // "If the rowid is not aliased by INTEGER PRIMARY KEY then it is not persistent and might change."

 if !matches!(
  columns.iter().find(|c| c.name == "rowid"),
  Some(Column { sql_type: "INTEGER PRIMARY KEY", .. })
 ) {
  abort_call_site!("derive(Turbosql) structs must include a 'rowid: Option<i64>' field")
 };

 columns
}

use std::fs;

/// CREATE TABLE
fn create(table: &Table) {
 // create the migrations

 let sql = makesql_create(&table);

 rusqlite::Connection::open_in_memory().unwrap().execute(&sql, params![]).unwrap_or_else(|e| {
  abort_call_site!("Error validating auto-generated CREATE TABLE statement: {} {:#?}", sql, e)
 });

 let target_migrations = make_migrations(&table);

 // read in the existing migrations from toml

 let lockfile = std::fs::File::create(std::env::temp_dir().join("migrations.toml.lock")).unwrap();
 fs2::FileExt::lock_exclusive(&lockfile).unwrap();

 let migrations_toml_path = std::env::current_dir().unwrap().join(MIGRATIONS_FILENAME);
 let migrations_toml_path_lossy = migrations_toml_path.to_string_lossy();

 let old_toml_str = if migrations_toml_path.exists() {
  fs::read_to_string(&migrations_toml_path)
   .unwrap_or_else(|e| abort_call_site!("Unable to read {}: {:?}", migrations_toml_path_lossy, e))
 } else {
  String::new()
 };

 let source_migrations_toml: MigrationsToml = toml::from_str(&old_toml_str).unwrap_or_else(|e| {
  abort_call_site!("Unable to decode toml in {}: {:?}", migrations_toml_path_lossy, e)
 });

 // add any migrations that aren't already present

 let mut output_migrations = source_migrations_toml.migrations_append_only.unwrap_or_default();

 target_migrations.iter().for_each(|target_m| {
  if output_migrations
   .iter()
   .find(|source_m| (source_m == &target_m) || (source_m == &&format!("--{}", target_m)))
   .is_none()
  {
   output_migrations.push(target_m.clone());
  }
 });

 let tables = match source_migrations_toml.output_generated_tables_do_not_edit {
  Some(ref t) => {
   let mut t = t.clone();
   TABLES.lock().unwrap().iter().for_each(|(k, v)| {
    t.insert(k.clone(), v.clone());
   });
   t
  }
  None => TABLES.lock().unwrap().clone(),
 };

 // save to toml

 let mut new_toml_str = String::new();
 let mut serializer = toml::Serializer::pretty(&mut new_toml_str);
 serializer.pretty_array_indent(2);

 MigrationsToml {
  output_generated_schema_for_your_information_do_not_edit: Some(format!(
   "  {}\n",
   migrations_to_schema(&output_migrations)
    .unwrap()
    .replace("\n", "\n  ")
    .replace("(", "(\n    ")
    .replace(", ", ",\n    ")
    .replace(")", "\n  )")
  )),
  migrations_append_only: Some(output_migrations),
  output_generated_tables_do_not_edit: Some(tables),
 }
 .serialize(&mut serializer)
 .unwrap_or_else(|e| abort_call_site!("Unable to serialize migrations toml: {:?}", e));

 let new_toml_str = indoc::formatdoc! {"
  # This file is auto-generated by Turbosql.
  # It is used to create and apply automatic schema migrations.
  # It should be checked into source control.
  # Modifying it by hand may be dangerous; see the docs.

  {}", &new_toml_str};

 // Only write migrations.toml file if it has actually changed;
 // this keeps file mod date clean so cargo doesn't pathologically rebuild

 if old_toml_str != new_toml_str {
  fs::write(&migrations_toml_path, new_toml_str)
   .unwrap_or_else(|e| abort_call_site!("Unable to write {}: {:?}", migrations_toml_path_lossy, e));
 }
}

fn makesql_create(table: &Table) -> String {
 format!(
  "CREATE TABLE {} ({})",
  table.name,
  table.columns.iter().map(|c| format!("{} {}", c.name, c.sql_type)).collect::<Vec<_>>().join(",")
 )
}

fn make_migrations(table: &Table) -> Vec<String> {
 let mut vec = vec![format!("CREATE TABLE {} (rowid INTEGER PRIMARY KEY)", table.name)];

 let mut alters = table
  .columns
  .iter()
  .filter_map(|c| match (c.name.as_str(), c.sql_type) {
   ("rowid", "INTEGER PRIMARY KEY") => None,
   _ => Some(format!("ALTER TABLE {} ADD COLUMN {} {}", table.name, c.name, c.sql_type)),
  })
  .collect::<Vec<_>>();

 vec.append(&mut alters);

 vec
}