From ec53ee2bda1a63b27025601b9b8e4710434207a2 Mon Sep 17 00:00:00 2001 From: Lucas Faria Mendes Date: Fri, 5 Dec 2025 06:51:08 -0300 Subject: codecrafters submit [skip ci] --- src/main.zig | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) (limited to 'src/main.zig') diff --git a/src/main.zig b/src/main.zig index 780c70c..c06bd66 100755 --- a/src/main.zig +++ b/src/main.zig @@ -37,6 +37,41 @@ pub fn main() !void { try stdout.print("number of tables: {}\n", .{num_tables}); } else if (std.mem.eql(u8, args[2], ".tables")) { try tables.showTables(allocator, &file, page_size, stdout); + } else if (std.mem.startsWith(u8, args[2], "SELECT") or std.mem.startsWith(u8, args[2], "select")) { + // Parse SELECT query: "SELECT column FROM table" + var tokens = std.mem.tokenizeScalar(u8, args[2], ' '); + + // Skip "SELECT" + _ = tokens.next(); + + // Get column name or aggregate function + const column_name = tokens.next() orelse return error.InvalidQuery; + + // Skip "FROM" or "from" + _ = tokens.next(); + + // Get table name + const table_name = tokens.next() orelse return error.InvalidQuery; + + // Check if this is COUNT(*) + if (std.mem.indexOf(u8, column_name, "count(") != null or std.mem.indexOf(u8, column_name, "COUNT(") != null) { + const rootpage = try schema.getRootpage(allocator, &file, page_size, table_name); + const row_count = try schema.countRows(allocator, &file, page_size, rootpage); + try stdout.print("{}\n", .{row_count}); + } else { + // Get the CREATE TABLE statement to find column order + const create_sql = try schema.getCreateTableSQL(allocator, &file, page_size, table_name); + defer allocator.free(create_sql); + + // Find the column index + const column_idx = try schema.parseColumnIndex(create_sql, column_name); + + // Get the table's root page + const rootpage = try schema.getRootpage(allocator, &file, page_size, table_name); + + // Read and print all rows + try schema.readTableRows(allocator, &file, page_size, rootpage, column_idx, stdout); + } } else { var tokens = std.mem.tokenizeScalar(u8, args[2], ' '); var last_token: []const u8 = ""; -- cgit v1.2.3