Deadlines
In the lab assignments in CS 133 you will write a basic database management system called SimpleDB. For this lab, you will focus on implementing the core modules required to access stored data on disk; in future labs, you will add support for various query processing operators, as well as transactions, locking, and concurrent queries.
SimpleDB is written in Java. We have provided you with a set of mostly unimplemented classes and interfaces. You will need to write the code for these classes. We will grade your code by running a set of unit and system tests written using JUnit.
Throughout the lab writeup you will see numbered exercises, offset in boxes, that describe where you should write code and which unit tests you should expect to pass once you are done. The due dates above correspond to these exercises. Note that there is no code to write for Exercise 0.
The remainder of this document describes the basic architecture of SimpleDB, and gives suggestions for coding, including the exercises you should complete. Section 3.2 discusses how to submit your code for both Part 1 and the Final version of the lab.
We strongly recommend that you start as early as possible on this lab. It requires you to write a fair amount of code!
Quick jump to exercises:
Jump to Submission instructions.
These instructions are written for a Unix-based platform (e.g., Linux, MacOS, etc.) Because the code is written in Java, it should work under Windows as well, though the directions in this document may need to be adjusted.
SimpleDB uses the Ant build tool to compile the code and run tests. Ant is similar to make, but the build file is written in XML and is somewhat better suited to Java code. Most modern Linux distributions include Ant.
You will need to use a programming environment that supports
Download the code from
http://www.cs.hmc.edu/~beth/courses/cs133/lab/cs133-lab1.tar.gz
and untar it.
For example, you can do this by issuing the following commands on the command line (the "$" is the command prompt):
$ wget http://www.cs.hmc.edu/~beth/courses/cs133/lab/cs133-lab1.tar.gz $ tar xvzkf cs133-lab1.tar.gz $ cd cs133-lab1
To help you during development, we have provided a set of unit tests in addition to the end-to-end system tests discussed in Section 1.1. These are by no means comprehensive, and you should not rely on them exclusively to verify the correctness of your lab.
To run the unit tests use the test
build target:
$ cd cs133-lab1 $ # run all unit tests $ ant test $ # run a specific unit test $ ant runtest -Dtest=TupleTestYou should see output similar to:
# build output... test: [junit] Running simpledb.CatalogTest [junit] Testsuite: simpledb.CatalogTest [junit] Tests run: 6, Failures: 5, Errors: 1, Skipped: 0, Time elapsed: 0.079 sec [junit] Tests run: 6, Failures: 5, Errors: 1, Skipped: 0, Time elapsed: 0.079 sec # ... stack traces and error reports ...
The output above indicates that two errors occurred during compilation; this is because the code we have given you doesn't yet work. As you complete parts of the lab, you will work towards passing additional unit tests. If you wish to write new unit tests as you code, they should be added to the test/simpledb directory.
For more details about how to use Ant,
see the manual. The
Running Ant section
provides details about using the ant
command. However, the quick
reference table below should be sufficient for working on the labs.
Command | Description |
---|---|
ant | Build the default target (for simpledb, this is dist). |
ant -projecthelp | List all the targets in build.xml with descriptions. |
ant javadocs | Build javadoc documentation |
ant dist | Compile the code in src and package it in dist/simpledb.jar. |
ant test | Compile and run all the unit tests. |
ant runtest -Dtest=testname | Run the unit test named testname. |
ant systemtest | Compile and run all the system tests. |
ant runsystest -Dtest=testname | Compile and run the system test named testname. |
ant handin | Generate tarball for submission. |
(a) Try to run the TupleDescTest unit test to make sure that you are able to compile the code:
If you are using ant, use this command to run just TupleDescTest:
ant runtest -Dtest=TupleDescTest
You should see in the output that the tests have errors, e.g., a java.lang.AssertionError indicating assertions in the unit test are failing and probably a java.lang.NullPointerException too. This make sense since you haven't written any code yet! At the bottom of the output, you should see something like the following:
BUILD FAILED The following error occurred while executing this line: Test simpledb.TupleDescTest failedYou should not see something like "Compile failed".
If you are using Eclipse, see our Eclipse guide for setup. Then be sure to run TupleDescTest to familiarize yourself with viewing unit test results.
(b) Now run the ant target to generate documentation:
ant javadocs
A directory called javadoc should have been created inside your cs133-lab1 directory. Note: in Eclipse, you may need to refresh the project contents in Package Explorer to see it (right-click the project name and find "refresh"). Open the file index.html in a web browser (or inside of Eclipse). Yay documentation!
In addition to small unit tests, such as TupleDescTest, we have also provided a set of end-to-end
tests, called system tests, for checking the functionality of the system you have built so far. These tests are structured as
JUnit tests that live in the test/simpledb/systemtest directory. To
run all the system tests, use the systemtest
build target:
$ ant systemtest # ... build output ... [junit] Testcase: testSmall took 0.017 sec [junit] Caused an ERROR [junit] expected to find the following tuples: [junit] 19128 [junit] [junit] java.lang.AssertionError: expected to find the following tuples: [junit] 19128 [junit] [junit] at simpledb.systemtest.SystemTestUtil.matchTuples(SystemTestUtil.java:122) [junit] at simpledb.systemtest.SystemTestUtil.matchTuples(SystemTestUtil.java:83) [junit] at simpledb.systemtest.SystemTestUtil.matchTuples(SystemTestUtil.java:75) [junit] at simpledb.systemtest.ScanTest.validateScan(ScanTest.java:30) [junit] at simpledb.systemtest.ScanTest.testSmall(ScanTest.java:40) # ... more error messages ...
This indicates that this test failed, showing the stack trace where the error was detected. To debug, start by reading the source code where the error occurred. When the tests pass, you will see something like the following:
$ ant systemtest # ... build output ... [junit] Testsuite: simpledb.systemtest.ScanTest [junit] Tests run: 3, Failures: 0, Errors: 0, Time elapsed: 7.278 sec [junit] Tests run: 3, Failures: 0, Errors: 0, Time elapsed: 7.278 sec [junit] [junit] Testcase: testSmall took 0.937 sec [junit] Testcase: testLarge took 5.276 sec [junit] Testcase: testRandom took 1.049 sec BUILD SUCCESSFUL Total time: 52 seconds
HeapFile
format using the command:
$ java -jar dist/simpledb.jar convert file.txt Nwhere file.txt is the name of the file and N is the number of columns in the file. Note: dist/simpledb.jar is created after running ant dist. Notice that file.txt has to be in the following format:
int1,int2,...,intN int1,int2,...,intN int1,int2,...,intN int1,int2,...,intN
...where each intN is a non-negative integer. Be sure file.txt ends in a newline.
Note: To run the Jar file from within Eclipse instead of on the command-line, see the directions in "Running a Jar file Using Eclipse" in our Eclipse guide.
To view the contents of a table, use the print
command:
$ java -jar dist/simpledb.jar print file.dat N
where file.dat is the name of a table created with the convert command, and N is the number of columns in the file.
Before beginning to write code, we strongly encourage you to read through this entire document to get a feel for the high-level design of SimpleDB.
You will need to fill in any piece of code that is not implemented. It should be obvious from the comments within and above each Java method where we think you should write code. You may need to add private methods, instance variables, and/or helper classes. You may change APIs, but make sure our grading tests still run and make sure to mention, explain, and defend your decisions in your writeup.
In addition to the methods that you need to fill out for this lab, the class interfaces contain numerous methods that you need not implement until subsequent labs. These will either be indicated per class:
// Not necessary for lab1. public class Insert implements DbIterator {or per method:
public boolean deleteTuple(Tuple t) throws DbException { // some code goes here // not necessary for lab1 return false; }The code that you submit should compile without having to modify these methods.
Section 2 below walks you through the implementation steps for this lab and the unit tests corresponding to each one in more detail.
SimpleDB does not include many things that you may think of as being a part of a "database." In particular, SimpleDB does not have:
In the rest of this Section, we describe each of the main components of SimpleDB that you will need to implement in this lab. You should use the exercises in this discussion to guide your implementation. This document is by no means a complete specification for SimpleDB; you will need to make decisions about how to design and implement various parts of the system. Note that for Lab 1 you do not need to implement any operators (e.g., select, join, project) except sequential scan. You will add support for additional operators in future labs.
Tuples in SimpleDB are quite basic. They consist of a collection of
Field
objects, one per field in the Tuple
.
Field
is an interface that different data types (e.g.,
integer, string) implement; see IntField
and StringField
.
Tuple
objects are created by the
underlying access methods (e.g., heap files, or B-trees), as described in
the next section. Tuples also have a type (or schema), called a tuple
descriptor, represented by a TupleDesc
object. This TupleDesc
object consists of a collection of Type
objects, one per field
in the tuple, each of which describes the type of the corresponding field.
If a tuple is stored on disk, it will have a RecordId
that identifies where
in a file the tuple is located.
RecordId.java
yet.
Some helpful notes:
Tuple
will need a data structure to hold its Fields
; looking at how Tuple
will need to use that data structure will help you pick one.if (someCondition) throw new NoSuchElementException();
Catalog
in SimpleDB) keeps track of the
tables and the schemas of the tables that are currently in the database. You will
need to support the ability to add a new table, as well as getting information
about a particular table. Associated with each table, or DbFile
, is
a TupleDesc
object that allows query plan operators to determine the types
and number of fields in a table.
The global catalog is a single instance
of Catalog
that is allocated for the entire SimpleDB process.
The global catalog can be retrieved via the method
Database.getCatalog()
, and the same goes for the
global buffer pool (using Database.getBufferPool()
).
At this point, your code should pass the unit tests in CatalogTest.
Some helpful notes:
Catalog
to see what lookup functionality it will support (the Javadoc is helpful for this!).int
in collections like ArrayList
or Iterator
. Check out the wrapper class java.lang.Integer
.The Buffer Pool (class BufferPool
in SimpleDB) is responsible
for caching pages in memory that have been recently read from disk. All
operators read and write pages from various files on disk through the buffer
pool. The Buffer Pool consists of a fixed number of pages, defined by the
numPages
parameter to the BufferPool
constructor.
In later labs, you will implement an
eviction policy. For this lab, you only need to implement the constructor and
the BufferPool.getPage()
method used by the Sequential Scan (SeqScan) operator.
The BufferPool should store up to numPages
pages. For this
lab, if more than numPages
requests are made for different
pages, then instead of implementing an eviction policy, you will throw a
DbException
. In a future lab you will be required to implement an eviction
policy.
Recall that the Database
class provides a static method,
Database.getBufferPool()
, that returns a reference to the single
BufferPool instance for the entire SimpleDB process.
getPage()
method in:
Some helpful notes:
DbFile.readPage
method to access pages of a DbFile. Think about how to get the correct DbFile!PageId
and Page
.tid
or perm
since you won't be implementing transactions and locking until Lab 4.DbFile
interface,
such as HeapFile
.
A HeapFile
object provides access to a set of pages stored on disk, each of which
consists of a fixed number of bytes for storing tuples, (defined by the constant
BufferPool.PAGE_SIZE
), including a header. In SimpleDB, there is one
HeapFile
object for each table in the database.
Each page in
a HeapFile
is arranged as a set of slots, each of which can hold
one tuple (tuples for a given table in SimpleDB are all of the same size). In
addition to these slots, each page has a header that consists of a bitmap with
one bit per tuple slot. If the bit corresponding to a particular tuple is 1,
it indicates that the tuple is valid; if it is 0, the tuple is invalid (e.g.,
has been deleted or was never initialized). Recall that a tuple's RecordId
indicates which page (of the file) and which slot on that page the tuple is located.
Pages of HeapFile
objects are of type HeapPage
, which implements the
Page
interface. Pages are stored in the Buffer Pool but are read
and written to/from disk using the HeapFile
class.
SimpleDB stores the pages in heap files on disk in more or less the same format they are stored in memory. Each file consists of page data arranged consecutively on disk. Each page consists of one or more bytes representing the header, followed by the page size bytes of actual page content. Each tuple requires tuple size * 8 bits for its content and 1 bit for the header. Thus, the number of tuples that can fit in a single page is:
tuples per page = floor((page size * 8) / (tuple size * 8 + 1))
Where tuple size is the size of a tuple in the page in bytes. The idea here is that each tuple requires one additional bit of storage in the header. We compute the number of bits in a page (by mulitplying page size by 8), and divide this quantity by the number of bits in a tuple (including this extra header bit) to get the number of tuples per page. The floor operation rounds down to the nearest integer number of tuples (we don't want to store partial tuples on a page!)
Once we know the number of tuples per page, the number of bytes required to store the header is simply:
headerBytes = ceiling(tupsPerPage/8)
The ceiling operation rounds up to the nearest integer number of bytes (we never store less than a full byte of header information.)
The low (least significant) bits of each byte represents the status of the slots that are earlier in the file. Hence, the lowest bit of the first byte represents whether or not the first slot in the page is in use. Also, note that the high-order bits of the last byte may not correspond to a slot that is actually in the file, since the number of slots may not be a multiple of 8. Also note that all Java virtual machines are big-endian.
Although you will not use them directly in Lab 1, we ask you to implement getNumEmptySlots() and isSlotFree() in HeapPage. These require manipulating bits in the page header. You may find it helpful to look at the other methods that have been provided in HeapPage or in src/simpledb/HeapFileEncoder.java to understand the layout of pages.
At this point, your code should pass the unit tests in HeapPageIdTest, RecordIDTest, and HeapPageReadTest.
Some helpful notes:
HeapPage
constructor, however it is worth
reading since it calls methods you will implementhasNext()
repeatedly without skipping elements;
calling next()
twice in a row should yield consecutive items.
Now that you have implemented HeapPage, you will write methods for HeapFile in this lab to calculate the number of pages in a file and to read a page from the file. HeapFile is given the filename, represented as an instance of a java.io.File, that it will read from. After implementing HeapFile, you will then be able to fetch tuples from a file stored on disk!
To read a page from disk, you will first need to calculate the correct
offset in the file. Hint: you will need random access to the file in
order to read and write pages at arbitrary offsets. You should not call
BufferPool methods when reading a page from disk. Instead, use the
File
passed into the constructor.
You will also need to implement the
HeapFile.iterator()
method, which should provide an Iterator of type DbFileIterator to iterate
through through the tuples of each page in the HeapFile. The iterator must
use the BufferPool.getPage()
method to access pages in the
HeapFile
. This method loads the page into
the buffer pool and will eventually be used (in a later lab) to
implement locking-based concurrency control and recovery. Do
not load the entire table into memory on the open() call in the Iterator -- this
will cause an out of memory error for very large tables!
At this point, your code should pass the unit tests in HeapFileReadTest.
Some helpful notes:
DbIterator
interface.
Operators are connected together into a query execution plan, or simply "plan", by passing operators as input into other operators via their constructors, i.e., by 'chaining them together', forming a tree of operators. Access method operators at the leaves of the plan are responsible for reading data from the disk (and hence do not have any operators below them).
At the top of the query plan tree, the program interacting with SimpleDB simply calls
getNext
on the root operator; this operator then calls
getNext
on its children, and so on, until these leaf operators
are called. They fetch tuples from disk and pass them up the tree (as return
arguments to getNext
); tuples propagate up the plan in this way
until they are output at the root or combined or rejected by another operator
in the plan.
For this lab, you will only need to implement one SimpleDB operator, the sequential scan (SeqScan); this operator is one of the access methods at the leaves of a query plan.
This operator sequentially scans all of the tuples from
the pages of the table specified by the tableid
in the
constructor. This operator should access tuples through the
iterator()
method provided by the HeapFile
.
At this point, you should be able to complete the ScanTest system test. Good work!
Some helpful notes:
You will add other operators in subsequent labs.
The purpose of this section is to illustrate how these various components are connected together to process a simple query. Suppose you have a data file, "some_data_file.txt", with the following contents:
1,1,1 2,2,2 3,4,4
You can convert this into a binary file that SimpleDB can query as follows:
java -jar dist/simpledb.jar convert some_data_file.txt 3
Here, the argument "3" tells convert that the input has 3 columns.
The following code implements a
simple selection query over this file.
This code is equivalent to the SQL statement
SELECT * FROM some_data_file
.
package simpledb; import java.io.*; public class test { public static void main(String[] argv) { // construct a 3-column table schema Type types[] = new Type[]{ Type.INT_TYPE, Type.INT_TYPE, Type.INT_TYPE }; String names[] = new String[]{ "field0", "field1", "field2" }; TupleDesc descriptor = new TupleDesc(types, names); // create the table, associate it with some_data_file.dat // and tell the catalog about the schema of this table. HeapFile table1 = new HeapFile(new File("some_data_file.dat"), descriptor); Database.getCatalog().addTable(table1, "test"); // construct the query: we use a simple SeqScan, which spoonfeeds // tuples via its iterator. TransactionId tid = new TransactionId(); SeqScan f = new SeqScan(tid, table1.getId()); try { // and run it f.open(); while (f.hasNext()) { Tuple tup = f.next(); System.out.println(tup); } f.close(); Database.getBufferPool().transactionComplete(tid); } catch (Exception e) { System.out.println ("Exception : " + e); } } }
The table we create has three integer fields. To express this, we create
a TupleDesc
object and pass it an array of Type
objects, and optionally an array of String
field names. Once we
have created this TupleDesc
, we initialize
a HeapFile
object representing the table stored in
some_data_file.dat
. Once we have created the table, we add it to
the catalog. If this were a database server that was already running, we
would have this catalog information loaded. We need to load it explicitly to
make this code self-contained.
Once we have finished initializing the database system, we create a query
plan. Our plan consists only of the SeqScan
operator that
scans the tuples from disk. In general, these operators are instantiated
with references to the appropriate table (in the case of SeqScan
) or child
operator (in the case of e.g. Filter). The test program then repeatedly
calls hasNext
and next
on the SeqScan
operator. As tuples
are output from the SeqScan
, they are printed out on the
command line.
some_data_file.dat
file
in the top level directory. Then run:
ant java -classpath dist/simpledb.jar simpledb.testNote that
ant
compiles test.java
and generates a new jarfile that contains it.
You will submit a tarball of your code on Gradescope for intermediate deadlines and for your final version. You only need to include your writeup for the final version.
You can generate the tarball by using the ant handin target. This will create a file called cs133-lab.tar.gz that you can submit. You can rename the tarball file if you want, but the filename must end in tar.gz. The autograder won't be able to handle it if you package your code any other way!
Click Lab 1 on your Gradescope dashboard. For deadlines besides the final version,
you only need to upload cs133-lab.tar.gz.
For the final version: click Lab 1 and then click the "Resubmit" button on the bottom of the page ; upload both cs133-lab.tar.gz and writeup.txt containing your writeup.
If you worked with a partner, be sure to enter them as a group member on Gradescope after uploading your files.
Your grade for the lab will be based on the final version after all exercises are complete.
75% of your grade will be based on whether or not your code passes the test suite. Before handing in your code, you should make sure it produces no errors (passes all of the tests) from both ant test and ant systemtest.
Important: before testing, we will replace your build.xml and the entire contents of the test directory with our version of these files. This means you cannot change the format of .dat files! You should also be careful changing our APIs. You should test that your code compiles the unmodified tests. In other words, we will untar your tarball, replace the files mentioned above, compile it, and then grade it. It will look roughly like this:
$ tar xvzf cs133-lab.tar.gz [replace build.xml and test] $ ant test $ ant systemtest
If any of these commands fail, we'll be unhappy, and, therefore, so will your grade.
An additional 25% of your grade will be based on the quality of your writeup, our subjective evaluation of your code, and on-time submission for the intermediate deadlines.
ENJOY!!