sql.cpp 13 KB

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