CSE 544, Winter 2009, Assignment 2

SimpleDB

Due: Friday, 6 February 2009, 11:00pm

 

Acknowledgement

This assignment comes from Prof. Sam Madden's 6.830 class at MIT.

 

Assignment 2 Clarifications

  1. Please let us know if you encounter any problems with this assignment. We will post clarifications and fixes here as necessary.

 

Assignment goal

In this assignment and the next one, you will write a basic database management system called SimpleDB. For this assignment, you will focus on implementing the core modules required to access stored data on disk; in the next assignment, you will add support for various query processing operators. We will not ask you to add transactions, locking, and concurrent queries because quarters are so short. However, we invite you to think how you would add such functionality into the system.

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 system tests written using JUnit. We have also provided a number of unit tests, which we will not use for grading but that you may find useful in verifying that your code works.

The remainder of this document describes the basic architecture of SimpleDB, gives some suggestions about how to start coding, and discusses how to hand in your assignment.

We strongly recommend that you start as early as possible on this assignment. It requires you to write a fair amount of code!

 

0. Find bugs, be patient, earn candy bars

SimpleDB is a relatively complex piece of code. It is very possible you are going to find bugs, inconsistencies, and bad, outdated, or incorrect documentation, etc.

We ask you, therefore, to do this assignment with an adventurous mindset. Don't get mad if something is not clear, or even wrong; rather, try to figure it out yourself or send us a friendly email. We promise to help out by posting bug fixes, new tarballs, etc., as bugs and issues are reported.

...and if you find a bug in our code, we'll give you a candy bar from the Benson store (see Section 3.3)!


1. Getting started

These instructions are written for any 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 not apply.

We have included Section 1.2 on using the project with Eclipse.

Download the code from http://www.cs.washington.edu/education/courses/544/09wi/assignments/hw2.tar.gz and untar it. For example:

$ wget http://www.cs.washington.edu/education/courses/544/09wi/assignments/hw2.tar.gz
$ tar zxvf hw2.tar.gz
$ cd 544-hw2

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.

To help you during development, we have provided a set of unit tests in addition to the end-to-end tests that we use for grading. These are by no means comprehensive, and you should not rely on them exclusively to verify the correctness of your project.

To run the unit tests use the test build target:

$ cd 544-hw2
$ # run all unit tests
$ ant test
$ # run a specific unit test
$ ant runtest -Dtest=TupleTest

You should see output similar to:

# build output...

test:
  [junit] Running simpledb.TupleTest
  [junit] Testsuite: simpledb.TupleTest
  [junit] Tests run: 3, Failures: 0, Errors: 3, Time elapsed: 0.036 sec
  [junit] Tests run: 3, Failures: 0, Errors: 3, Time elapsed: 0.036 sec
  
# ... stack traces and error reports ...

The output above indicates that three errors occurred during compilation; this is because the code we have given you doesn't yet work. As you complete parts of the assignment, 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 assignments.

CommandDescription
antBuild the default target (for simpledb, this is dist).
ant -projecthelpList all the targets in build.xml with descriptions.
ant distCompile the code in src and package it in dist/simpledb.jar.
ant testCompile and run all the unit tests.
ant runtest -Dtest=testnameRun the unit test named testname.
ant systemtestCompile and run all the system tests.
ant runsystest -Dtest=testnameCompile and run the system test named testname.


1.1. Running end-to-end tests

We have also provided a set of end-to-end tests that will eventually be used for grading. 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 ...

systemtest:

[junit] Running simpledb.systemtest.ScanTest
  [junit] Testsuite: simpledb.systemtest.ScanTest
  [junit] Tests run: 3, Failures: 0, Errors: 3, Time elapsed: 0.237 sec
  [junit] Tests run: 3, Failures: 0, Errors: 3, Time elapsed: 0.237 sec
  [junit] 
  [junit] Testcase: testSmall took 0.017 sec
  [junit] 	Caused an ERROR
  [junit] implement this
  [junit] java.lang.UnsupportedOperationException: implement this
  [junit] 	at simpledb.HeapFile.id(HeapFile.java:46)
  [junit] 	at simpledb.systemtest.SystemTestUtil.matchTuples(SystemTestUtil.java:90)
  [junit] 	at simpledb.systemtest.SystemTestUtil.matchTuples(SystemTestUtil.java:83)
  [junit] 	at simpledb.systemtest.ScanTest.validateScan(ScanTest.java:30)
  [junit] 	at simpledb.systemtest.ScanTest.testSmall(ScanTest.java:41)
    
# ... 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

 

1.1.1 Creating dummy tables


It is likely you'll want to create your own tests and your own data tables to test your own implementation of SimpleDB. You can create any .txt file and convert it to a .dat file in SimpleDB's HeapFile format using the command:

$ ant dist

$ java -jar dist/simpledb.jar convert file.txt N

where file.txt is the name of the file and N is the number of columns in the file. 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.

To view the contents of a table, use the print command. Note that this command will not work until later in the assignment:

$ 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.


1.2. Working in Eclipse

Eclipse is a graphical software development environment that you might be more comfortable with working in. The instructions we provide were generated by using Eclipse 3.4.0 (Ganymede) for Java Developers (not the enterprise edition) with Java 1.5.0_13 on Ubuntu 7.10. They should also work under Windows or on MacOS.

Setting the Assignment Up in Eclipse

Running Individual Unit and System Tests

To run a unit test or system test (both are JUnit tests, and can be initialized the same way), go to the Package Explorer tab on the left side of your screen. Under the "544-hw2" project, open the "test" directory. Unit tests are found in the "simpledb" package, and system tests are found in the "simpledb.systemtests" package. To run one of these tests, select the test (they are all called *Test.java - don't select TestUtil.java or SystemTestUtil.java), right click on it, select "Run As," and select "JUnit Test." This will bring up a JUnit tab, which will tell you the status of the individual tests within the JUnit test suite, and will show you exceptions and other errors that will help you debug problems.

Running Ant Build Targets

If you want to run commands such as "ant test" or "ant systemtest," right click on build.xml in the Package Explorer. Select "Run As" and then "Ant Build..." (note: select the option with the ellipsis (...), otherwise you won't be presented with a set of build targets to run). Then, in the "Targets" tab of the next screen, check off the targets you want to run (probably "dist" and one of "test" or "systemtest"). This should run the build targets and show you the results in Eclipse's console window.


1.3. Implementation hints

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 will be obvious where we think you should write code. You may need to add private methods 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 assignment, the class interfaces contain numerous methods that you need not implement in this assignment. These will either be indicated per class:

// Not necessary for assignment 1.
public class Insert implements DbIterator {

or per method:

public boolean deleteTuple(Tuple t) throws DbException {

  // Some code goes here
  // Not necessary for assignment 1
  return false;
}

The code that you submit should compile without having to modify these methods.

We suggest exercises along this document to guide your implementation, but you may find that a different order makes more sense for you. Here's a rough outline of one way you might proceed with your SimpleDB implementation:

Section 2 below walks you through these implementation steps and the unit tests corresponding to each one in more detail.

 

1.4. Transactions, locking, and recovery

As you look through the interfaces that we have provided you, you will see a number of references to locking, transactions, and recovery. You do not need to support these features. We will not be implementing this part of SimpleDB this quarter. It is there because we may use it in subsequent quarters.The test code we have provided you with generates a fake transaction ID that is passed into the operators of the query it runs; you should pass this transaction ID into other operators and the buffer pool.


2. SimpleDB Architecture and Implementation Guide

SimpleDB consists of:

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 assignment. 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 Assignment 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 assignments.

You may also wish to consult the JavaDoc for SimpleDB which you can find in the tar file we have provided you under: 544-hw2/doc/index.html.


2.1. The Database Class

The Database class provides access to a collection of static objects that are the global state of the database. In particular, this includes methods to access the catalog (the list of all the tables in the database), the buffer pool (the collection of database file pages that are currently resident in memory), and the log file. You will not need to worry about the log file in this assignment. We have implemented the Database class for you. You should take a look at this file as you will need to access these objects.


2.2. Fields and Tuples

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. 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 object consists of a collection of Type objects, one per field in the tuple, each of which describes the type of the corresponding field.

Exercise 1. Implement the skeleton methods in:

   src/simpledb/TupleDesc.java
   src/simpledb/Tuple.java


At this point, your code should pass the unit tests TupleTest and TupleDescTest.

2.3. Catalog

The catalog (class Catalog in SimpleDB) consists of a list of the tables and 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 is a TupleDesc object that allows operators to determine the types and number of fields in a table.

To learn more about catalogs in a DBMS, take a look at Section 12.1 of the R&G book.

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()).


Exercise 2. Implement the skeleton methods in:



   src/simpledb/Catalog.java


At this point, your code should pass the unit tests in CatalogTest.

2.4. BufferPool

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. It consists of a fixed number of pages, defined by the numPages parameter to the BufferPool constructor. In later assignments, you will implement an eviction policy. For this assignment, you only need to implement the constructor and the BufferPool.getPage() method used by the SeqScan operator. The BufferPool should store up to numPages pages. For this assignment, if more than numPages requests are made for different pages, then instead of implementing an eviction policy, you may throw a DbException. In future assignments you will be required to implement an eviction policy.

The Database class provides a static method, Database.getBufferPool(), that returns a reference to the single BufferPool instance for the entire SimpleDB process.


Exercise 3. Implement the getPage() method in:

   src/simpledb/BufferPool.java

We have not provided unit tests for BufferPool. The functionality you implemented will be tested in the implementation of HeapFile below. You should use the DbFile.readPage method to access pages of a DbFile.


2.5. HeapFile access method


Access methods provide a way to read or write data from disk that is arranged in a specific way. Common access methods include heap files (unsorted files of tuples) and B-trees; for this assignment, you will only implement a heap file access method, and we have written some of the code for you.

A HeapFile object is arranged into a set of pages, each of which consists of a fixed number of bytes for storing tuples, (defined by the constant BufferPool.PAGE_SIZE), plus 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.) 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 by the HeapFile class.

SimpleDB stores 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 32-bit integers representing the header, followed by the BufferPool.PAGE_SIZE bytes of actual page content. The number of 32-bit integers in the header is defined by the formula:

((BufferPool.PAGE_SIZE / tuple size) / 32 ) +1 )

Where tuple size is the size of a tuple in the page in bytes.

The low (least significant) bits of each integer represent the status of the slots that are earlier in the file. Hence, the lowest bit of the first integer represents whether or not the first slot in the page is in use. Also, note that the high-order bits of the last such integer may not correspond to a slot that is actually in the file, since the number of slots may not be a multiple of 32. Also note that all Java virtual machines are big-endian.

The page content of each page consists of floor(BufferPool.PAGE_SIZE/tuple size) tuple slots, where the 0-indexed ith slot begins i * tuple size bytes into the page.


Exercise 4. Implement the skeleton methods in:

   src/simpledb/HeapPageId.java
   src/simpledb/RecordID.java
   src/simpledb/HeapPage.java


Although you will not use them directly in Assignment 1, we ask you to implement getNumEmptySlots() and getSlot() in HeapPage. These require pushing around 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.

You will also need to implement an Iterator over the tuples in the page, which may involve an auxiliary class or data structure.

At this point, your code should pass the unit tests in HeapPageIdTest, RecordIDTest, and HeapPageReadTest.

After you have implemented HeapPage, you will write methods for HeapFile in this assignment to calculate the number of pages in a file and to read a page from the file. You will then be able to fetch tuples from a file stored on disk.


Exercise 5. Implement the skeleton methods in:

   src/simpledb/HeapFile.java


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 will also need to implement the HeapFile.iterator() method, which should 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 assignment) to implement locking-based concurrency control and recovery.

At this point, your code should pass the unit tests in HeapFileReadTest.


2.6. Operators

Operators are responsible for the actual execution of the query plan. They implement the operations of the relational algebra. In SimpleDB, operators are iterator based; each operator implements the DbIterator interface.

Operators are connected together into a plan by passing lower-level operators into the constructors of higher-level operators, i.e., by 'chaining them together.' Special 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 plan, 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 assignment, you will only need to implement one SimpleDB operator.


Exercise 6. Implement the skeleton methods in:

   src/simpledb/SeqScan.java


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 DbFile.iterator() method.

At this point, you should be able to complete the ScanTest system test. Good work!

You will fill in other operators in subsequent assignments.


2.7. A simple query

The purpose of this section is to illustrate how these various components are connected together to process a simple query. The following code implements a simple selection query over a data file consisting of three columns of integers. (The file some_data_file.dat is a binary representation of the pages from this file). This code is equivalent to the SQL statement SELECT * FROM some_data_file.

  // 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"));
  Database.getCatalog().addTable(table1, descriptor);

  // Construct the query: we use a simple SeqScan, which spoonfeeds
  // tuples via its iterator.
  TransactionId tid = new TransactionId();
  SeqScan       f   = new SeqScan(tid, table1.id());
  
  // ...and run it
  f.open();
  
  while (f.hasNext()) {
  	  Tuple tup = f.next();
  	  System.out.println(tup);
  }
  f.close();
  
  Database.getBufferPool().transactionComplete(tid);
  

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.


Turn in instructions

You must submit your code (see below) as well as a short (2 pages, maximum) writeup describing your approach. This writeup should:

To submit your code, please create a hw2.tar.gz tarball (such that, untarred, it creates a 544-hw2/src/simpledb directory with your code) and email it to your TA.

You may submit your code multiple times; we will use the latest version you submit that arrives before the deadline (before 10:59 PM on the due date). If applicable, please indicate your partner in your email. Please also attach your individual writeup as a PDF or text file.

Submitting a bug

Please submit (friendly!) bug reports to the TA and instructor. When you do, please try to include:

If you are the first person to report a particular bug in the code, we will give you a Benson-store candy bar!


Grading

75% of your grade will be based on whether or not your code passes the system test suite we will run over it. These tests will be a superset of the tests we have provided. 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 hw2.tar.gz
$ cd ./544-hw2
[replace build.xml and test]
$ ant test
$ ant systemtest
[additional tests]

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 and our subjective evaluation of your code.

We hope you will enjoy this assignment and will learn a lot about how a simple DBMS system can be implemented!