sql.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  1. /*
  2. * Copyright (c) 2021, Tim Flynn <trflynn89@pm.me>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Format.h>
  7. #include <AK/String.h>
  8. #include <AK/StringBuilder.h>
  9. #include <LibCore/ArgsParser.h>
  10. #include <LibCore/File.h>
  11. #include <LibCore/StandardPaths.h>
  12. #include <LibLine/Editor.h>
  13. #include <LibSQL/AST/Lexer.h>
  14. #include <LibSQL/AST/Token.h>
  15. #include <LibSQL/SQLClient.h>
  16. #include <unistd.h>
  17. class SQLRepl {
  18. public:
  19. explicit SQLRepl(String const& database_name)
  20. : m_loop()
  21. {
  22. m_editor = Line::Editor::construct();
  23. m_editor->load_history(m_history_path);
  24. m_editor->on_display_refresh = [this](Line::Editor& editor) {
  25. editor.strip_styles();
  26. int open_indents = m_repl_line_level;
  27. auto line = editor.line();
  28. SQL::AST::Lexer lexer(line);
  29. bool indenters_starting_line = true;
  30. for (SQL::AST::Token token = lexer.next(); token.type() != SQL::AST::TokenType::Eof; token = lexer.next()) {
  31. auto start = token.start_position().column - 1;
  32. auto end = token.end_position().column - 1;
  33. if (indenters_starting_line) {
  34. if (token.type() != SQL::AST::TokenType::ParenClose)
  35. indenters_starting_line = false;
  36. else
  37. --open_indents;
  38. }
  39. switch (token.category()) {
  40. case SQL::AST::TokenCategory::Invalid:
  41. editor.stylize({ start, end }, { Line::Style::Foreground(Line::Style::XtermColor::Red), Line::Style::Underline });
  42. break;
  43. case SQL::AST::TokenCategory::Number:
  44. editor.stylize({ start, end }, { Line::Style::Foreground(Line::Style::XtermColor::Magenta) });
  45. break;
  46. case SQL::AST::TokenCategory::String:
  47. editor.stylize({ start, end }, { Line::Style::Foreground(Line::Style::XtermColor::Green), Line::Style::Bold });
  48. break;
  49. case SQL::AST::TokenCategory::Blob:
  50. editor.stylize({ start, end }, { Line::Style::Foreground(Line::Style::XtermColor::Magenta), Line::Style::Bold });
  51. break;
  52. case SQL::AST::TokenCategory::Keyword:
  53. editor.stylize({ start, end }, { Line::Style::Foreground(Line::Style::XtermColor::Blue), Line::Style::Bold });
  54. break;
  55. case SQL::AST::TokenCategory::Identifier:
  56. editor.stylize({ start, end }, { Line::Style::Foreground(Line::Style::XtermColor::White), Line::Style::Bold });
  57. break;
  58. default:
  59. break;
  60. }
  61. }
  62. m_editor->set_prompt(prompt_for_level(open_indents));
  63. };
  64. m_sql_client = SQL::SQLClient::try_create().release_value_but_fixme_should_propagate_errors();
  65. m_sql_client->on_connected = [this](int connection_id, String const& connected_to_database) {
  66. outln("Connected to \033[33;1m{}\033[0m", connected_to_database);
  67. m_current_database = connected_to_database;
  68. m_pending_database = "";
  69. m_connection_id = connection_id;
  70. read_sql();
  71. };
  72. m_sql_client->on_execution_success = [this](int, bool has_results, int updated, int created, int deleted) {
  73. if (updated != 0 || created != 0 || deleted != 0) {
  74. outln("{} row(s) updated, {} created, {} deleted", updated, created, deleted);
  75. }
  76. if (!has_results) {
  77. read_sql();
  78. }
  79. };
  80. m_sql_client->on_next_result = [](int, Vector<String> const& row) {
  81. StringBuilder builder;
  82. builder.join(", ", row);
  83. outln("{}", builder.build());
  84. };
  85. m_sql_client->on_results_exhausted = [this](int, int total_rows) {
  86. outln("{} row(s)", total_rows);
  87. read_sql();
  88. };
  89. m_sql_client->on_connection_error = [this](int, int code, String const& message) {
  90. outln("\033[33;1mConnection error:\033[0m {}", message);
  91. m_loop.quit(code);
  92. };
  93. m_sql_client->on_execution_error = [this](int, int, String const& message) {
  94. outln("\033[33;1mExecution error:\033[0m {}", message);
  95. read_sql();
  96. };
  97. m_sql_client->on_disconnected = [this](int) {
  98. if (m_pending_database.is_empty()) {
  99. outln("Disconnected from \033[33;1m{}\033[0m and terminating", m_current_database);
  100. m_loop.quit(0);
  101. } else {
  102. outln("Disconnected from \033[33;1m{}\033[0m", m_current_database);
  103. m_current_database = "";
  104. m_sql_client->connect(m_pending_database);
  105. }
  106. };
  107. if (!database_name.is_empty())
  108. connect(database_name);
  109. }
  110. ~SQLRepl()
  111. {
  112. m_editor->save_history(m_history_path);
  113. }
  114. void connect(String const& database_name)
  115. {
  116. if (m_current_database.is_empty()) {
  117. m_sql_client->connect(database_name);
  118. } else {
  119. m_pending_database = database_name;
  120. m_sql_client->async_disconnect(m_connection_id);
  121. }
  122. }
  123. void source_file(String file_name)
  124. {
  125. m_input_file_chain.append(move(file_name));
  126. m_quit_when_files_read = false;
  127. }
  128. void read_file(String file_name)
  129. {
  130. m_input_file_chain.append(move(file_name));
  131. m_quit_when_files_read = true;
  132. }
  133. auto run()
  134. {
  135. return m_loop.exec();
  136. }
  137. private:
  138. String m_history_path { String::formatted("{}/.sql-history", Core::StandardPaths::home_directory()) };
  139. RefPtr<Line::Editor> m_editor { nullptr };
  140. int m_repl_line_level { 0 };
  141. bool m_keep_running { true };
  142. String m_pending_database {};
  143. String m_current_database {};
  144. AK::RefPtr<SQL::SQLClient> m_sql_client { nullptr };
  145. int m_connection_id { 0 };
  146. Core::EventLoop m_loop;
  147. RefPtr<Core::File> m_input_file { nullptr };
  148. bool m_quit_when_files_read { false };
  149. Vector<String> m_input_file_chain {};
  150. Optional<String> get_line()
  151. {
  152. if (!m_input_file && !m_input_file_chain.is_empty()) {
  153. auto file_name = m_input_file_chain.take_first();
  154. auto file_or_error = Core::File::open(file_name, Core::OpenMode::ReadOnly);
  155. if (file_or_error.is_error()) {
  156. warnln("Input file {} could not be opened: {}", file_name, file_or_error.error());
  157. return {};
  158. }
  159. m_input_file = file_or_error.value();
  160. }
  161. if (m_input_file) {
  162. auto line = m_input_file->read_line();
  163. if (m_input_file->eof()) {
  164. m_input_file->close();
  165. m_input_file = nullptr;
  166. if (m_quit_when_files_read && m_input_file_chain.is_empty())
  167. return {};
  168. }
  169. return line;
  170. // If the last file is exhausted but m_quit_when_files_read is false
  171. // we fall through to the standard reading from the editor behaviour
  172. }
  173. auto line_result = m_editor->get_line(prompt_for_level(m_repl_line_level));
  174. if (line_result.is_error())
  175. return {};
  176. return line_result.value();
  177. }
  178. String read_next_piece()
  179. {
  180. StringBuilder piece;
  181. do {
  182. if (!piece.is_empty())
  183. piece.append('\n');
  184. auto line_maybe = get_line();
  185. if (!line_maybe.has_value()) {
  186. m_keep_running = false;
  187. return {};
  188. }
  189. auto& line = line_maybe.value();
  190. auto lexer = SQL::AST::Lexer(line);
  191. m_editor->add_to_history(line);
  192. piece.append(line);
  193. bool is_first_token = true;
  194. bool is_command = false;
  195. bool last_token_ended_statement = false;
  196. for (SQL::AST::Token token = lexer.next(); token.type() != SQL::AST::TokenType::Eof; token = lexer.next()) {
  197. switch (token.type()) {
  198. case SQL::AST::TokenType::ParenOpen:
  199. ++m_repl_line_level;
  200. break;
  201. case SQL::AST::TokenType::ParenClose:
  202. --m_repl_line_level;
  203. break;
  204. case SQL::AST::TokenType::SemiColon:
  205. last_token_ended_statement = true;
  206. break;
  207. case SQL::AST::TokenType::Period:
  208. if (is_first_token)
  209. is_command = true;
  210. break;
  211. default:
  212. last_token_ended_statement = is_command;
  213. break;
  214. }
  215. is_first_token = false;
  216. }
  217. m_repl_line_level = last_token_ended_statement ? 0 : (m_repl_line_level > 0 ? m_repl_line_level : 1);
  218. } while ((m_repl_line_level > 0) || piece.is_empty());
  219. return piece.to_string();
  220. }
  221. void read_sql()
  222. {
  223. String piece = read_next_piece();
  224. // m_keep_running can be set to false when the file we are reading
  225. // from is exhausted...
  226. if (!m_keep_running) {
  227. m_sql_client->async_disconnect(m_connection_id);
  228. return;
  229. }
  230. if (piece.starts_with('.')) {
  231. handle_command(piece);
  232. } else {
  233. auto statement_id = m_sql_client->sql_statement(m_connection_id, piece);
  234. m_sql_client->async_statement_execute(statement_id);
  235. }
  236. // ...But m_keep_running can also be set to false by a command handler.
  237. if (!m_keep_running) {
  238. m_sql_client->async_disconnect(m_connection_id);
  239. return;
  240. }
  241. };
  242. static String prompt_for_level(int level)
  243. {
  244. static StringBuilder prompt_builder;
  245. prompt_builder.clear();
  246. prompt_builder.append("> ");
  247. for (auto i = 0; i < level; ++i)
  248. prompt_builder.append(" ");
  249. return prompt_builder.build();
  250. }
  251. void handle_command(StringView command)
  252. {
  253. if (command == ".exit" || command == ".quit") {
  254. m_keep_running = false;
  255. } else if (command.starts_with(".connect ")) {
  256. auto parts = command.split_view(' ');
  257. if (parts.size() == 2)
  258. connect(parts[1]);
  259. else
  260. outln("\033[33;1mUsage: .connect <database name>\033[0m");
  261. } else if (command.starts_with(".read ")) {
  262. if (!m_input_file) {
  263. auto parts = command.split_view(' ');
  264. if (parts.size() == 2) {
  265. source_file(parts[1]);
  266. } else {
  267. outln("\033[33;1mUsage: .read <sql file>\033[0m");
  268. }
  269. } else {
  270. outln("\033[33;1mCannot recursively read sql files\033[0m");
  271. }
  272. m_loop.deferred_invoke([this]() {
  273. read_sql();
  274. });
  275. } else {
  276. outln("\033[33;1mUnrecognized command:\033[0m {}", command);
  277. }
  278. }
  279. };
  280. int main(int argc, char** argv)
  281. {
  282. String database_name(getlogin());
  283. String file_to_source;
  284. String file_to_read;
  285. bool suppress_sqlrc = false;
  286. auto sqlrc_path = String::formatted("{}/.sqlrc", Core::StandardPaths::home_directory());
  287. Core::ArgsParser args_parser;
  288. args_parser.set_general_help("This is a client for the SerenitySQL database server.");
  289. args_parser.add_option(database_name, "Database to connect to", "database", 'd', "database");
  290. args_parser.add_option(file_to_read, "File to read", "read", 'r', "file");
  291. args_parser.add_option(file_to_source, "File to source", "source", 's', "file");
  292. args_parser.add_option(suppress_sqlrc, "Don't read ~/.sqlrc", "no-sqlrc", 'n');
  293. args_parser.parse(argc, argv);
  294. SQLRepl repl(database_name);
  295. if (!suppress_sqlrc && Core::File::exists(sqlrc_path))
  296. repl.source_file(sqlrc_path);
  297. if (!file_to_source.is_empty())
  298. repl.source_file(file_to_source);
  299. if (!file_to_read.is_empty())
  300. repl.read_file(file_to_read);
  301. return repl.run();
  302. }