sql.cpp 13 KB

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