sql.cpp 12 KB

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