sql.cpp 13 KB

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