Rapture ORM sample code
| import rapture.orm._ | |
| object TestDb extends App { | |
| // Create a database pool | |
| val DbPool = new PostgresDbPool("localhost", "conferencedb", "operator", "letmein") | |
| // Define the database schema | |
| implicit object Conference extends Table(new Conference) { | |
| def allActive()(implicit db : Db) = selectFrom("WHERE active").all() | |
| } | |
| class Conference extends IdRecord("Conference") { | |
| val name = field[String] | |
| val venue = optional(refField[Location]) | |
| def delegates()(implicit db : Db) = Delegate.selectFrom("WHERE conference = ?", this).all() | |
| } | |
| implicit object Delegate extends Table(new Delegate) { | |
| def all()(implicit db : Db) = selectFrom("").all() | |
| } | |
| class Delegate extends IdRecord("Delegate") { | |
| val name = field[String] | |
| val company = field[String] | |
| val conference = refField[Conference] | |
| } | |
| implicit object Location extends Table(new Location) { | |
| def findByName(n : String)(implicit db : Db) = selectFrom("WHERE location = ?", n).option() | |
| } | |
| object Country extends Enumeration { val Us, Uk, Fr, Ch, De = Value } | |
| class Location extends IdRecord("Location") { | |
| val name = field[String] | |
| val country = enumField(Country) | |
| def conferences()(implicit db : Db) = Conference.selectFrom("WHERE location = ?", this).all() | |
| } | |
| // Get a connection from the pool | |
| DbPool.acquireFor { implicit db => | |
| // This will create the database tables on an empty database, or modify existing tables to match | |
| // the schema above | |
| DbPool.migrateSql(Conference, Delegate, Location).foreach(cmd => Db.exec(cmd)) | |
| // Add some records | |
| val loc = new Location { | |
| name() = "Philadelphia" | |
| country() = Country.Us | |
| save() | |
| } | |
| val c = new Conference { | |
| name() = "Scalathon" | |
| venue() = Some(loc.ref) | |
| save() | |
| } | |
| val d = new Delegate { | |
| name() = "Jon Pretty" | |
| company() = "Propensive Ltd" | |
| conference() = c.ref | |
| save() | |
| } | |
| // Returns the location record | |
| Location.findByName("Philadelphia") | |
| // Returns a (Conference, Location) pair | |
| (Conference -> "c" | Location -> "l").select(""" | |
| FROM Conference c INNER JOIN Location l ON c.location = l.id | |
| """).all() | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment