├── .gitignore ├── LICENSE ├── Makefile ├── README.md ├── docs ├── 01-REPL.md └── 02-REPL.md ├── include └── repl.h └── src ├── main.c └── repl.c /.gitignore: -------------------------------------------------------------------------------- 1 | # Ignore compiled binaries and object files 2 | sqlite_clone 3 | build/ 4 | .vscode/ 5 | 6 | # Prerequisites 7 | *.d 8 | 9 | # Object files 10 | *.o 11 | *.ko 12 | *.obj 13 | *.elf 14 | 15 | # Linker output 16 | *.ilk 17 | *.map 18 | *.exp 19 | 20 | # Precompiled Headers 21 | *.gch 22 | *.pch 23 | 24 | # Libraries 25 | *.lib 26 | *.a 27 | *.la 28 | *.lo 29 | 30 | # Shared objects (inc. Windows DLLs) 31 | *.dll 32 | *.so 33 | *.so.* 34 | *.dylib 35 | 36 | # Executables 37 | *.exe 38 | *.out 39 | *.app 40 | *.i*86 41 | *.x86_64 42 | *.hex 43 | 44 | # Debug files 45 | *.dSYM/ 46 | *.su 47 | *.idb 48 | *.pdb 49 | 50 | # Kernel Module Compile Results 51 | *.mod* 52 | *.cmd 53 | .tmp_versions/ 54 | modules.order 55 | Module.symvers 56 | Mkfile.old 57 | dkms.conf 58 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | CC = gcc 2 | CFLAGS = -Wall -Wextra -g 3 | SRC_DIR = src 4 | BUILD_DIR = build 5 | INCLUDE_DIR = include 6 | 7 | SRC_FILES = $(wildcard $(SRC_DIR)/*.c) 8 | OBJ_FILES = $(patsubst $(SRC_DIR)/%.c, $(BUILD_DIR)/%.o, $(SRC_FILES)) 9 | TARGET = sqlite 10 | 11 | all: $(TARGET) 12 | 13 | $(TARGET): $(OBJ_FILES) 14 | $(CC) $(CFLAGS) -o $@ $^ 15 | 16 | $(BUILD_DIR)/%.o: $(SRC_DIR)/%.c | $(BUILD_DIR) 17 | $(CC) $(CFLAGS) -I$(INCLUDE_DIR) -c $< -o $@ 18 | 19 | $(BUILD_DIR): 20 | mkdir -p $(BUILD_DIR) 21 | 22 | clean: 23 | rm -rf $(BUILD_DIR) $(TARGET) 24 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Certainly! Here's the updated documentation with the resource included: 2 | 3 | # simple-database-c 4 | 5 | A **lightweight SQLite clone** written in C, designed to explore how databases work from the ground up. This project walks through building a simple relational database step by step, covering key concepts like indexing, transactions, and storage formats. 6 | 7 | ## 🚀 Why This Project? 8 | Ever wondered **how databases actually work under the hood**? 9 | 10 | - How is data stored in memory and on disk? 11 | - What makes transactions and rollbacks possible? 12 | - How do indexes speed up queries? 13 | - What happens when a table gets too big? 14 | 15 | This project is a hands-on attempt to **build a database from scratch** to understand these concepts deeply. 16 | 17 | ## 🔧 Features 18 | - 🖥️ **Interactive REPL** to run SQL-like commands 19 | - 📝 **Basic SQL compiler & virtual machine** 20 | - 📂 **File-based storage** for persistence 21 | - 🌳 **B-Tree indexing** for fast lookups 22 | - 🔄 **Transaction support** with rollbacks 23 | - 🔍 **Binary search for efficient queries** 24 | 25 | ## 📚 What You’ll Learn 26 | - The **fundamentals of database storage** (memory & disk) 27 | - How **SQL queries** are processed behind the scenes 28 | - How **B-Trees** work and why they’re used in databases 29 | - The **mechanics of transactions** and rollbacks 30 | - The basics of writing a **mini SQL engine** in C 31 | 32 | ## 🏗️ How It’s Built (Step by Step) 33 | 1. Setting up a simple **REPL** 34 | 2. Building a **SQL compiler & virtual machine** 35 | 3. ~~Implementing an **in-memory database**~~ 36 | 4. ~~Adding **file storage** for persistence~~ 37 | 5. ~~Creating a **cursor abstraction** for data traversal~~ 38 | 6. ~~Implementing **B-Trees** for indexing~~ 39 | 7. ~~Handling **binary search & duplicate keys**~~ 40 | 8. ~~Splitting **leaf & internal nodes**~~ 41 | 9. ~~Supporting **multi-level B-Tree traversal**~~ 42 | 10. ~~Optimizing query execution~~ 43 | 44 | ## 🛠️ Getting Started 45 | ### Required Tools 46 | - **C Compiler**: Ensure you have GCC or another C compiler installed. 47 | - **Make**: Used to build the project. 48 | 49 | Clone the repo and compile it using a C compiler: 50 | 51 | ```sh 52 | git clone https://github.com/proXDhiya/simple-database-c.git 53 | cd simple-database-c 54 | make 55 | ./sqlite 56 | ``` 57 | 58 | Now you’re ready to start **experimenting with database internals! 🚀** 59 | 60 | > This project is inspired by SQLite’s architecture and is meant for learning and fun. It follows the tutorial available at [cstack's DB tutorial](https://cstack.github.io/db_tutorial/). Feel free to contribute or tweak it to explore database internals further! 61 | -------------------------------------------------------------------------------- /docs/01-REPL.md: -------------------------------------------------------------------------------- 1 | # REPL Implementation for Simple Database 2 | 3 | This document provides an overview of the Read-Eval-Print Loop (REPL) implementation for the Simple Database project. The REPL allows users to interactively input and execute commands, making it an essential component for testing and exploring database functionalities. 4 | 5 | ## Overview 6 | 7 | The REPL is implemented in C, providing an interactive shell for users to input commands. It is designed to handle basic input operations and execute specific commands like `.exit`. 8 | 9 | ### Key Components 10 | 11 | - **Header File (`repl.h`)**: Defines the structure and function prototypes. 12 | - **Source File (`repl.c`)**: Implements the REPL logic. 13 | 14 | ## `repl.h` 15 | 16 | ### Structure 17 | 18 | ```c 19 | typedef struct { 20 | char* buffer; 21 | size_t buffer_length; 22 | ssize_t input_length; 23 | } InputBuffer; 24 | ``` 25 | 26 | - **`buffer`**: A dynamically allocated string to store user input. 27 | - **`buffer_length`**: The size of the allocated buffer. 28 | - **`input_length`**: The length of the input string. 29 | 30 | ### Functions 31 | 32 | - **`InputBuffer* new_input_buffer();`**: Allocates and initializes a new `InputBuffer`. 33 | - **`void print_prompt();`**: Displays the input prompt to the user. 34 | - **`void read_input(InputBuffer* input_buffer);`**: Reads user input into the buffer. 35 | - **`void close_input_buffer(InputBuffer* input_buffer);`**: Frees allocated memory for the input buffer. 36 | - **`void start_repl();`**: Initiates the REPL loop for continuous input processing. 37 | 38 | ## `repl.c` 39 | 40 | ### Function Implementations 41 | 42 | #### `InputBuffer* new_input_buffer()` 43 | 44 | - Allocates memory for a new `InputBuffer`. 45 | - Initializes `buffer` to `NULL`, `buffer_length` and `input_length` to `0`. 46 | 47 | #### `void print_prompt()` 48 | 49 | - Prints `"db > "` to signal readiness for input. 50 | 51 | #### `void read_input(InputBuffer* input_buffer)` 52 | 53 | - Utilizes `getline()` to read input from the user. 54 | - Dynamically adjusts `buffer` size and stores the input length. 55 | - Removes the trailing newline character for cleaner processing. 56 | 57 | #### `void close_input_buffer(InputBuffer* input_buffer)` 58 | 59 | - Frees the memory allocated for both the buffer and the `InputBuffer` structure. 60 | 61 | #### `void start_repl()` 62 | 63 | - Initializes a new `InputBuffer`. 64 | - Enters a loop to continuously read and process input. 65 | - Recognizes the `.exit` command to terminate the REPL. 66 | 67 | ### Example Workflow 68 | 69 | 1. **Start REPL**: Initializes input buffer and displays prompt. 70 | 2. **Read Input**: Waits for user input and reads it into the buffer. 71 | 3. **Process Input**: Checks for specific commands, such as `.exit`. 72 | 4. **Repeat**: Continues the loop for further input, unless an exit command is received. 73 | 74 | ## Conclusion 75 | 76 | The REPL implementation provides a simple yet effective way to interact with the Simple Database. It facilitates easy testing and exploration of database functionalities, laying the groundwork for more advanced features. 77 | -------------------------------------------------------------------------------- /docs/02-REPL.md: -------------------------------------------------------------------------------- 1 | # Updated REPL Implementation for Simple Database 2 | 3 | This document provides an overview of the enhanced Read-Eval-Print Loop (REPL) implementation for the Simple Database project. The REPL allows users to interactively input and execute commands, making it an essential component for testing and exploring database functionalities. 4 | 5 | ## Overview 6 | 7 | The REPL is implemented in C, providing an interactive shell for users to input commands. It now supports basic SQL-like commands and meta-commands, enhancing its functionality. 8 | 9 | ### Key Components 10 | 11 | - **Header File (`repl.h`)**: Defines structures, enums, and function prototypes. 12 | - **Source File (`repl.c`)**: Implements the REPL logic and command handling. 13 | 14 | ## `repl.h` 15 | 16 | ### Enums and Structures 17 | 18 | #### MetaCommandResult 19 | 20 | ```c 21 | typedef enum { 22 | META_COMMAND_SUCCESS, 23 | META_COMMAND_UNRECOGNIZED_COMMAND 24 | } MetaCommandResult; 25 | ``` 26 | 27 | - Indicates the result of executing a meta-command. 28 | 29 | #### PrepareResult 30 | 31 | ```c 32 | typedef enum { 33 | PREPARE_SUCCESS, 34 | PREPARE_UNRECOGNIZED_STATEMENT 35 | } PrepareResult; 36 | ``` 37 | 38 | - Represents the outcome of preparing a SQL statement. 39 | 40 | #### StatementType 41 | 42 | ```c 43 | typedef enum { 44 | STATEMENT_INSERT, 45 | STATEMENT_SELECT 46 | } StatementType; 47 | ``` 48 | 49 | - Defines types of SQL statements supported. 50 | 51 | #### InputBuffer 52 | 53 | ```c 54 | typedef struct { 55 | char* buffer; 56 | size_t buffer_length; 57 | ssize_t input_length; 58 | } InputBuffer; 59 | ``` 60 | 61 | - Stores user input dynamically. 62 | 63 | #### Statement 64 | 65 | ```c 66 | typedef struct { 67 | StatementType type; 68 | } Statement; 69 | ``` 70 | 71 | - Represents a parsed SQL statement. 72 | 73 | ### Functions 74 | 75 | - **`InputBuffer* new_input_buffer();`**: Allocates and initializes a new `InputBuffer`. 76 | - **`void print_prompt();`**: Displays the input prompt to the user. 77 | - **`void read_input(InputBuffer* input_buffer);`**: Reads user input into the buffer. 78 | - **`void close_input_buffer(InputBuffer* input_buffer);`**: Frees allocated memory for the input buffer. 79 | - **`void start_repl();`**: Initiates the REPL loop for continuous input processing. 80 | - **`MetaCommandResult do_meta_command(InputBuffer* input_buffer);`**: Executes a meta-command. 81 | - **`PrepareResult prepare_statement(InputBuffer* input_buffer, Statement* statement);`**: Parses and prepares an SQL statement. 82 | - **`void execute_statement(Statement* statement);`**: Executes the prepared SQL statement. 83 | 84 | ## `repl.c` 85 | 86 | ### Function Implementations 87 | 88 | #### `InputBuffer* new_input_buffer()` 89 | 90 | - Allocates memory for a new `InputBuffer`. 91 | - Initializes `buffer` to `NULL`, `buffer_length` and `input_length` to `0`. 92 | 93 | #### `void print_prompt()` 94 | 95 | - Prints `"db > "` to signal readiness for input. 96 | 97 | #### `void read_input(InputBuffer* input_buffer)` 98 | 99 | - Utilizes `getline()` to read input from the user. 100 | - Dynamically adjusts `buffer` size and stores the input length. 101 | - Removes the trailing newline character for cleaner processing. 102 | 103 | #### `void close_input_buffer(InputBuffer* input_buffer)` 104 | 105 | - Frees the memory allocated for both the buffer and the `InputBuffer` structure. 106 | 107 | #### `MetaCommandResult do_meta_command(InputBuffer* input_buffer)` 108 | 109 | - Processes meta-commands like `.exit`. 110 | - Returns a result indicating success or an unrecognized command. 111 | 112 | #### `PrepareResult prepare_statement(InputBuffer* input_buffer, Statement* statement)` 113 | 114 | - Parses input to determine if it matches supported SQL commands (`insert`, `select`). 115 | - Returns a result indicating success or an unrecognized statement. 116 | 117 | #### `void execute_statement(Statement* statement)` 118 | 119 | - Executes the parsed SQL statement. 120 | - Currently contains placeholders for `insert` and `select`. 121 | 122 | #### `void start_repl()` 123 | 124 | - Initializes a new `InputBuffer`. 125 | - Enters a loop to continuously read and process input. 126 | - Handles both SQL and meta-commands, terminating on `.exit`. 127 | 128 | ### Example Workflow 129 | 130 | 1. **Start REPL**: Initializes input buffer and displays prompt. 131 | 2. **Read Input**: Waits for user input and reads it into the buffer. 132 | 3. **Process Meta-Commands**: Handles commands starting with a dot. 133 | 4. **Prepare SQL Commands**: Parses and prepares SQL-like commands. 134 | 5. **Execute Commands**: Executes recognized commands. 135 | 6. **Repeat**: Continues the loop for further input, unless an exit command is received. 136 | 137 | ## Conclusion 138 | 139 | The updated REPL implementation provides a more robust interface for interacting with the Simple Database. It supports basic SQL commands and meta-commands, paving the way for further development and enhancements. -------------------------------------------------------------------------------- /include/repl.h: -------------------------------------------------------------------------------- 1 | #ifndef REPL_H 2 | #define REPL_H 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | // Enum for meta-command results 10 | typedef enum { 11 | META_COMMAND_SUCCESS, // Meta-command executed successfully 12 | META_COMMAND_UNRECOGNIZED_COMMAND // Meta-command not recognized 13 | } MetaCommandResult; 14 | 15 | // Enum for preparation results 16 | typedef enum { 17 | PREPARE_SUCCESS, // Statement prepared successfully 18 | PREPARE_UNRECOGNIZED_STATEMENT // Statement not recognized 19 | } PrepareResult; 20 | 21 | // Enum for statement types 22 | typedef enum { 23 | STATEMENT_INSERT, // Insert statement 24 | STATEMENT_SELECT // Select statement 25 | } StatementType; 26 | 27 | // Structure to store user input 28 | typedef struct { 29 | char* buffer; // Pointer to input string 30 | size_t buffer_length; // Size of the allocated buffer 31 | ssize_t input_length; // Length of the input string 32 | } InputBuffer; 33 | 34 | // Structure to represent a SQL statement 35 | typedef struct { 36 | StatementType type; // Type of statement (insert/select) 37 | } Statement; 38 | 39 | // Function prototypes for REPL operations 40 | 41 | /** 42 | * Allocates and initializes a new InputBuffer. 43 | * 44 | * @return A pointer to the newly created InputBuffer. 45 | */ 46 | InputBuffer* new_input_buffer(); 47 | 48 | /** 49 | * Displays the command prompt to the user. 50 | * 51 | * Typically used to indicate readiness for a new command. 52 | */ 53 | void print_prompt(); 54 | 55 | /** 56 | * Reads a line of input from the user into the provided InputBuffer. 57 | * 58 | * @param input_buffer A pointer to the InputBuffer where input will be stored. 59 | */ 60 | void read_input(InputBuffer* input_buffer); 61 | 62 | /** 63 | * Frees the memory allocated for the InputBuffer. 64 | * 65 | * @param input_buffer A pointer to the InputBuffer to be freed. 66 | */ 67 | void close_input_buffer(InputBuffer* input_buffer); 68 | 69 | /** 70 | * Initiates the Read-Eval-Print Loop (REPL). 71 | * 72 | * Continuously reads and processes user commands. 73 | */ 74 | void start_repl(); 75 | 76 | /** 77 | * Executes a meta-command entered by the user. 78 | * 79 | * @param input_buffer A pointer to the InputBuffer containing the command. 80 | * @return A MetaCommandResult indicating success or unrecognized command. 81 | */ 82 | MetaCommandResult do_meta_command(InputBuffer* input_buffer); 83 | 84 | /** 85 | * Parses the user input and prepares an SQL statement. 86 | * 87 | * @param input_buffer A pointer to the InputBuffer containing the SQL command. 88 | * @param statement A pointer to a Statement structure to store the parsed command. 89 | * @return A PrepareResult indicating success or unrecognized statement. 90 | */ 91 | PrepareResult prepare_statement(InputBuffer* input_buffer, Statement* statement); 92 | 93 | /** 94 | * Executes the prepared SQL statement. 95 | * 96 | * @param statement A pointer to the Statement to be executed. 97 | */ 98 | void execute_statement(Statement* statement); 99 | 100 | #endif // REPL_H 101 | -------------------------------------------------------------------------------- /src/main.c: -------------------------------------------------------------------------------- 1 | #include "repl.h" 2 | 3 | int main() 4 | { 5 | start_repl(); 6 | return 0; 7 | } 8 | -------------------------------------------------------------------------------- /src/repl.c: -------------------------------------------------------------------------------- 1 | #include "repl.h" 2 | 3 | // Create and initialize a new InputBuffer 4 | InputBuffer* new_input_buffer() { 5 | InputBuffer* input_buffer = malloc(sizeof(InputBuffer)); 6 | input_buffer->buffer = NULL; 7 | input_buffer->buffer_length = 0; 8 | input_buffer->input_length = 0; 9 | 10 | return input_buffer; 11 | } 12 | 13 | // Display the input prompt to the user 14 | void print_prompt() { 15 | printf("db > "); 16 | } 17 | 18 | // Read input from the user 19 | void read_input(InputBuffer* input_buffer) { 20 | ssize_t bytes_read = 21 | getline(&(input_buffer->buffer), &(input_buffer->buffer_length), stdin); 22 | 23 | if (bytes_read <= 0) { 24 | printf("Error reading input\n"); 25 | exit(EXIT_FAILURE); 26 | } 27 | 28 | // Ignore trailing newline 29 | input_buffer->input_length = bytes_read - 1; 30 | input_buffer->buffer[bytes_read - 1] = 0; 31 | } 32 | 33 | // Free memory of InputBuffer 34 | void close_input_buffer(InputBuffer* input_buffer) { 35 | free(input_buffer->buffer); 36 | free(input_buffer); 37 | } 38 | 39 | // Execute meta-command 40 | MetaCommandResult do_meta_command(InputBuffer* input_buffer) { 41 | if (strcmp(input_buffer->buffer, ".exit") == 0) { 42 | close_input_buffer(input_buffer); 43 | exit(EXIT_SUCCESS); 44 | } else { 45 | return META_COMMAND_UNRECOGNIZED_COMMAND; 46 | } 47 | } 48 | 49 | // Prepare SQL statement 50 | PrepareResult prepare_statement(InputBuffer* input_buffer, Statement* statement) { 51 | if (strncmp(input_buffer->buffer, "insert", 6) == 0) { 52 | statement->type = STATEMENT_INSERT; 53 | return PREPARE_SUCCESS; 54 | } 55 | if (strcmp(input_buffer->buffer, "select") == 0) { 56 | statement->type = STATEMENT_SELECT; 57 | return PREPARE_SUCCESS; 58 | } 59 | 60 | return PREPARE_UNRECOGNIZED_STATEMENT; 61 | } 62 | 63 | // Execute prepared statement 64 | void execute_statement(Statement* statement) { 65 | switch (statement->type) { 66 | case (STATEMENT_INSERT): 67 | printf("This is where we would do an insert.\n"); 68 | break; 69 | case (STATEMENT_SELECT): 70 | printf("This is where we would do a select.\n"); 71 | break; 72 | } 73 | } 74 | 75 | // Start the REPL loop 76 | void start_repl() { 77 | InputBuffer* input_buffer = new_input_buffer(); 78 | 79 | while (true) { 80 | print_prompt(); 81 | read_input(input_buffer); 82 | 83 | if (input_buffer->buffer[0] == '.') { 84 | switch (do_meta_command(input_buffer)) { 85 | case (META_COMMAND_SUCCESS): 86 | continue; 87 | case (META_COMMAND_UNRECOGNIZED_COMMAND): 88 | printf("Unrecognized command '%s'\n", input_buffer->buffer); 89 | continue; 90 | } 91 | } 92 | 93 | Statement statement; 94 | switch (prepare_statement(input_buffer, &statement)) { 95 | case (PREPARE_SUCCESS): 96 | break; 97 | case (PREPARE_UNRECOGNIZED_STATEMENT): 98 | printf("Unrecognized keyword at start of '%s'.\n", input_buffer->buffer); 99 | continue; 100 | } 101 | 102 | execute_statement(&statement); 103 | printf("Executed.\n"); 104 | } 105 | } 106 | --------------------------------------------------------------------------------