Skip to content

Database lab 3#8

Open
lindaeskilsson wants to merge 10 commits intomainfrom
database-lab-3
Open

Database lab 3#8
lindaeskilsson wants to merge 10 commits intomainfrom
database-lab-3

Conversation

@lindaeskilsson
Copy link

@lindaeskilsson lindaeskilsson commented Dec 10, 2025

Summary by CodeRabbit

  • Documentation

    • Updated README with review assignment information.
  • New Features

    • Introduced interactive command-line interface with user authentication.
    • Added mission data browsing: view all missions, search by ID, count missions by year.
    • Account management capabilities: create, update passwords, and delete accounts.
  • Chores

    • Updated build dependencies and packaging configuration.

✏️ Tip: You can customize this high-level summary in your review settings.

@coderabbitai
Copy link

coderabbitai bot commented Dec 10, 2025

Walkthrough

The changes introduce a persistent database connection architecture, add CLI-based user login and interactive menu system with multiple database operations (list missions, fetch by ID, count by year, account management), add slf4j-simple logging dependency, and update the Maven build configuration with classpath and main class manifest settings.

Changes

Cohort / File(s) Summary
Documentation
README.md
Added "Review Assignment Due Date" badge link at top of file.
Build Configuration
pom.xml
Added slf4j-simple runtime logging dependency (2.0.13) and maven-jar-plugin (3.2.2) with manifest configuration to include classpath and set main class to com.example.Main.
Application Core
src/main/java/com/example/Main.java
Replaced try-with-resources pattern with persistent instance connection field. Introduced CLI login flow (username/password validation against database) and interactive menu loop with operations: list moon missions, fetch mission by ID, count missions by year, create/update/delete accounts. Added 8 new private methods (login, printMenu, listMoonMissions, getMoonMissionById, countMissionsByYear, createAccount, updatePassword, deleteAccount) and adjusted error handling to throw RuntimeException on failures.

Sequence Diagram

sequenceDiagram
    actor User
    participant CLI as Main (CLI)
    participant DB as Database
    
    User->>CLI: Start application
    CLI->>DB: Establish connection
    DB-->>CLI: Connection ready
    
    CLI->>User: Prompt username/password
    User->>CLI: Enter credentials
    
    CLI->>DB: Query accounts table<br/>(login validation)
    DB-->>CLI: User found (or not found)
    
    alt Login Success
        CLI->>User: Display menu
        loop Menu Loop
            User->>CLI: Select operation<br/>(1-8 or 9 to exit)
            alt List Missions
                CLI->>DB: SELECT moon_mission
                DB-->>CLI: Mission data
                CLI->>User: Display missions
            else Fetch by ID
                CLI->>User: Prompt mission ID
                User->>CLI: Enter ID
                CLI->>DB: SELECT WHERE id=?
                DB-->>CLI: Mission details
                CLI->>User: Display mission
            else Count by Year
                CLI->>User: Prompt year
                User->>CLI: Enter year
                CLI->>DB: COUNT WHERE year=?
                DB-->>CLI: Count result
                CLI->>User: Display count
            else Account Operations
                CLI->>DB: INSERT/UPDATE/DELETE account
                DB-->>CLI: Operation result
                CLI->>User: Confirm operation
            else Exit
                CLI->>User: Goodbye
                CLI->>DB: Close connection
            end
        end
    else Login Failure
        CLI->>User: Display error message
        CLI->>DB: Close connection
    end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

  • Main.java contains substantial architectural changes: transition from immediate try-with-resources to persistent connection instance field requires verification of connection lifecycle and potential resource leak prevention
  • Login method and database credential validation logic need careful review for SQL injection vulnerabilities and authentication correctness
  • CLI menu loop control flow is new and requires tracing through all eight new private methods to ensure proper state management and error handling
  • Error handling strategy has changed from explicit resource management to RuntimeException propagation—verify this approach is consistent with application error handling patterns
  • Placeholder message anomaly: "Invalid username or password" appears in getMoonMissionById() when no record found; confirm if this is intended or a copy-paste error that should be corrected

Poem

🐰 A lunar CLI hops into view,
With login gates and missions too!
Through database halls the rabbit bounds,
While slf4j logs all the sounds!
From connection pools to menu's call,
This code takes interactive flight—hop it all! 🌙

Pre-merge checks and finishing touches

❌ Failed checks (1 inconclusive)
Check name Status Explanation Resolution
Title check ❓ Inconclusive The title 'Database lab 3' is vague and generic, using non-descriptive terms that don't convey meaningful information about the specific changes made in the changeset. Revise the title to be more specific and descriptive of the main changes, such as 'Add CLI database operations with login and account management' or 'Implement interactive database menu with authentication'.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Docstring Coverage ✅ Passed Docstring coverage is 90.00% which is sufficient. The required threshold is 80.00%.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (5)
src/main/java/com/example/Main.java (5)

100-110: Menu text mostly matches spec; consider aligning wording more closely

Functionally the menu is fine and options map 1:1 to the required operations. To minimize surprises with the tests and keep the UX aligned with the README, you might consider:

  • Making option 2 text closer to the spec, e.g. Get a moon mission by mission_id.
  • Optionally dropping or adjusting the " ---> MENU <--- " header if tests compare menu output strictly.

These are cosmetic, not functional.


112-126: Listing missions is correct; optional: add deterministic ordering

listMoonMissions selects spacecraft from moon_mission and prints each row, which is exactly what’s needed. If you want fully deterministic output (useful for tests), you could add an ORDER BY (for example, by mission_id):

-        String sql = "SELECT spacecraft FROM moon_mission";
+        String sql = "SELECT spacecraft FROM moon_mission ORDER BY mission_id";

Not required if the tests don’t care about order.


174-205: Account creation flow matches assignment; note about real‑world password handling

The createAccount method prompts for first name, last name, ssn, and password and inserts them with a prepared statement, then prints "created". That aligns well with the described behavior for option 4.

For the assignment this is fine; just keep in mind that in a real application you’d never store plaintext passwords or SSNs like this—hashing and strong access controls would be required.


208-228: Updating password works; optional feedback when no rows are affected

updatePassword performs a parameterized UPDATE on password by user_id and prints "updated" unconditionally. That’s functionally acceptable for the lab.

If you want slightly better UX, you could check executeUpdate()’s return value and print a different message when user_id doesn’t exist, but that’s not required by the assignment.


230-246: Delete account implementation is straightforward

deleteAccount deletes by user_id using a prepared statement and prints "deleted". This satisfies the option 6 requirement. Same as with update, you might later distinguish between “deleted” vs “no such user”, but it’s perfectly fine for the lab as‑is.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e629e94 and 3f7f144.

📒 Files selected for processing (3)
  • README.md (1 hunks)
  • pom.xml (1 hunks)
  • src/main/java/com/example/Main.java (2 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
src/main/java/com/example/Main.java (1)
src/main/java/com/example/DevDatabaseInitializer.java (1)
  • DevDatabaseInitializer (6-24)
🔇 Additional comments (5)
README.md (1)

1-1: Badge addition is fine

The new GitHub Classroom “Review Assignment Due Date” badge is purely informational and doesn’t affect build or runtime behavior. No changes needed.

src/main/java/com/example/Main.java (3)

3-10: Single shared Connection is fine for this CLI use case

Using a single Connection field that’s initialized once in run() and reused across the helpers keeps the implementation simple and matches the assignment’s level. No changes strictly required here.


83-96: Login implementation against account table looks good

login correctly uses a prepared statement with parameters on name and password, returning true on the first match and wrapping SQL errors in a runtime exception. This matches the described behavior and avoids SQL injection. No changes needed here.


33-80: Consider closing the DB connection on exit and double‑check user‑visible strings

The connection is opened and stored but never explicitly closed; in a short‑lived CLI this isn't a big problem, but it's still good practice to close it once the login/menu loop is done (e.g. in a finally block around the interactive part of run()).

Also, some messages are test‑sensitive per the README (e.g. wording around invalid). You might want to align exact strings with the assignment text (e.g. ensuring the word invalid appears in lower case where required) to avoid brittle test failures.

pom.xml (1)

49-53: [rewritten comment]
[classification tag]

Comment on lines +128 to +153
// todo: choice 2 - Get mission by ID
private void getMoonMissionById(Scanner scanner) {
System.out.print("mission_id: ");
int id = Integer.parseInt(scanner.nextLine());

String sql = "SELECT * FROM moon_mission WHERE mission_id = ?";

try (PreparedStatement stmt = connection.prepareStatement(sql)) {
stmt.setInt(1, id);
ResultSet rs = stmt.executeQuery();

if (rs.next()) {
System.out.println(
rs.getInt("mission_id") + " " +
rs.getString("spacecraft") + " " +
rs.getString("launch_date")
);
System.out.println("------------");
} else {
System.out.println("Invalid username or password");
}

} catch (SQLException e) {
throw new RuntimeException(e);
}
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Wrong error message when mission ID is not found

In getMoonMissionById, the else branch currently prints:

System.out.println("Invalid username or password");

This is misleading in the context of looking up a mission and will confuse users (and likely tests that expect a mission‑specific message).

Apply a small fix like:

-            } else {
-                System.out.println("Invalid username or password");
-            }
+            } else {
+                System.out.println("No mission found for that id");
+            }

Optionally, you may also want to validate that the entered ID is numeric and handle NumberFormatException with a simple invalid message, but that’s not strictly required by the assignment.

🤖 Prompt for AI Agents
In src/main/java/com/example/Main.java around lines 128 to 153, the else branch
prints an unrelated "Invalid username or password" message when no mission is
found; change that message to something mission‑appropriate (e.g., "Mission not
found" or "No mission with that ID") so users/tests get the correct feedback,
and optionally add a NumberFormatException catch around parsing the input to
print a simple "Invalid mission ID" message if non‑numeric input is entered.

Comment on lines +156 to +172
// todo: choice 3 - Count missions by year
private void countMissionsByYear(Scanner scanner) {
System.out.print("Total missions for 2019: ");
int year = Integer.parseInt(scanner.nextLine());

String sql = "SELECT COUNT(*) FROM moon_mission WHERE YEAR(launch_date) = ?";

try (PreparedStatement stmt = connection.prepareStatement(sql)) {
stmt.setInt(1, year);
ResultSet rs = stmt.executeQuery();
rs.next();
System.out.println(rs.getInt(1));

} catch (SQLException e) {
throw new RuntimeException(e);
}
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Prompt for year should not hardcode 2019

countMissionsByYear currently prompts:

System.out.print("Total missions for 2019: ");

but then reads an arbitrary year and queries using that year. This conflicts with the “given year” requirement and can be confusing.

A clearer and spec‑aligned version would be:

-        System.out.print("Total missions for 2019: ");
+        System.out.print("year: ");
         int year = Integer.parseInt(scanner.nextLine());

The rest of the query logic (using YEAR(launch_date) and printing the count) looks good.

🤖 Prompt for AI Agents
In src/main/java/com/example/Main.java around lines 156 to 172, the prompt
string currently hardcodes "Total missions for 2019: " which is inconsistent
with reading an arbitrary year; change the prompt to a generic, accurate message
(for example "Enter year: " or "Total missions for year: ") so the prompt is
shown before reading input and matches the year being parsed and used in the
query.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant