Created
January 14, 2015 15:36
-
-
Save nathanlws/59b3901da5cd890a1171 to your computer and use it in GitHub Desktop.
FoundationDB Key-Value Store Unique Constraint
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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, "[email protected]"); | |
| // same ID allowed | |
| app.insertUser(1, "[email protected]"); | |
| app.insertUser(2, "[email protected]"); | |
| try { | |
| app.insertUser(3, "[email protected]"); | |
| throw new IllegalStateException(); | |
| } catch(IllegalArgumentException e) { /* expected */ } | |
| app.insertUser(3, "[email protected]"); | |
| 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