sql_formatter.cpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. #include <yql/essentials/sql/v1/format/sql_format.h>
  2. #include <library/cpp/getopt/last_getopt.h>
  3. #include <google/protobuf/arena.h>
  4. #include <util/stream/file.h>
  5. int RunFormat(int argc, char* argv[]) {
  6. NLastGetopt::TOpts opts = NLastGetopt::TOpts::Default();
  7. TString outFileName;
  8. TString inFileName;
  9. TString queryString;
  10. opts.AddLongOption('o', "output", "save output to file").RequiredArgument("file").StoreResult(&outFileName);
  11. opts.AddLongOption('i', "input", "input file").RequiredArgument("input").StoreResult(&inFileName);
  12. opts.AddLongOption('p', "print-query", "print given query before parsing").NoArgument();
  13. opts.AddLongOption('f', "obfuscate", "obfuscate query").NoArgument();
  14. opts.AddLongOption("ansi-lexer", "use ansi lexer").NoArgument();
  15. opts.AddHelpOption();
  16. NLastGetopt::TOptsParseResult res(&opts, argc, argv);
  17. THolder<TFixedBufferFileOutput> outFile;
  18. if (!outFileName.empty()) {
  19. outFile.Reset(new TFixedBufferFileOutput(outFileName));
  20. }
  21. IOutputStream& out = outFile ? *outFile.Get() : Cout;
  22. THolder<TUnbufferedFileInput> inFile;
  23. if (!inFileName.empty()) {
  24. inFile.Reset(new TUnbufferedFileInput(inFileName));
  25. }
  26. IInputStream& in = inFile ? *inFile.Get() : Cin;
  27. queryString = in.ReadAll();
  28. int errors = 0;
  29. TString queryFile("query");
  30. if (res.Has("print-query")) {
  31. out << queryString << Endl;
  32. }
  33. google::protobuf::Arena arena;
  34. NSQLTranslation::TTranslationSettings settings;
  35. settings.Arena = &arena;
  36. settings.AnsiLexer = res.Has("ansi-lexer");
  37. auto formatter = NSQLFormat::MakeSqlFormatter(settings);
  38. TString frm_query;
  39. TString error;
  40. NYql::TIssues issues;
  41. if (!formatter->Format(queryString, frm_query, issues, res.Has("obfuscate") ?
  42. NSQLFormat::EFormatMode::Obfuscate : NSQLFormat::EFormatMode::Pretty)) {
  43. ++errors;
  44. Cerr << "Error formatting query: " << issues.ToString() << Endl;
  45. } else {
  46. out << frm_query;
  47. }
  48. return errors;
  49. }
  50. int main(int argc, char* argv[]) {
  51. try {
  52. return RunFormat(argc, argv);
  53. } catch (const yexception& e) {
  54. Cerr << "Caught exception:" << e.what() << Endl;
  55. return 1;
  56. } catch (...) {
  57. Cerr << CurrentExceptionMessage() << Endl;
  58. return 1;
  59. }
  60. return 0;
  61. }