Skip to content

Instantly share code, notes, and snippets.

@nathanlws
Created January 14, 2015 15:36
Show Gist options
  • Save nathanlws/59b3901da5cd890a1171 to your computer and use it in GitHub Desktop.
Save nathanlws/59b3901da5cd890a1171 to your computer and use it in GitHub Desktop.
FoundationDB Key-Value Store Unique Constraint
import com.foundationdb.*;
import com.foundationdb.async.*;
import com.foundationdb.directory.*;
import com.foundationdb.tuple.*;
public class UniqueDemo
{
public static void main(String[] args) {
FDB fdb = FDB.selectAPIVersion(200);
UniqueDemo app = new UniqueDemo(fdb);
test(app);
}
public static void test(UniqueDemo app) {
System.out.println("Testing");
app.insertUser(1, "foo@example.com");
// same ID allowed
app.insertUser(1, "foo@example.com");
app.insertUser(2, "bar@example.com");
try {
app.insertUser(3, "foo@example.com");
throw new IllegalStateException();
} catch(IllegalArgumentException e) { /* expected */ }
app.insertUser(3, "zap@example.com");
System.out.println("Passed");
}
final Database db;
final DirectorySubspace users;
final DirectorySubspace usersByEmail;
public UniqueDemo(FDB fdb) {
this.db = fdb.open();
this.users = DirectoryLayer.getDefault().createOrOpen(db, PathUtil.from("users")).get();
this.usersByEmail = DirectoryLayer.getDefault().createOrOpen(db, PathUtil.from("users_by_email")).get();
}
public void insertUser(final int userID, final String email) {
db.run(new Function<Transaction, Void>() {
@Override
public Void apply(Transaction tr) {
// Insert user into primary key index
tr.set(users.pack(userID), Tuple.from(userID, email).pack());
// UNIQUE constraint on email field. As in an RDBMS, this requires an
// index on the field. If you want, you can of course use this index
// for reads, too
byte[] curID = tr.get(usersByEmail.pack(email)).get();
if((curID != null) && (Tuple.fromBytes(curID).getLong(0) != userID)) {
throw new IllegalArgumentException("Duplicate e-mail address");
}
tr.set(usersByEmail.pack(email), Tuple.from(userID).pack());
return null;
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment