Slick编程简介

  categories:资料  tags:  author:

Slick对于Scala来说,有如LINQ至于C# ,或者类似于其它平台上的ORM系统,它使用应用使用数据库有如使用Scala内置的集合类型(比如列表,集合等)一样方便。当然如有需要你还是可以直接使用SQL语句来查询数据库。
下面为使用Slick的代码片段:
1    val limit = 10.0
2
3    // Your query could look like this:
4    ( for( c <- coffees; if c.price < limit ) yield c.name ).list
5
6    // Or using more plain SQL String Interpolation:
7    sql”select COF_NAME from COFFEES where PRICE < $limit”.as[String].list
8
9    // Both queries result in SQL equivalent to:
10    // select COF_NAME from COFFEES where PRICE < 10.0

使用Slick而不直接使用SQL语句,可以使用编译器帮助发现一些类型错误,同时Slick可以为不同的后台数据库类型生成查询。
它具有如下的一些特定:
Scala
所有查询,表格和字段映射,以及类型都采用普通的Scala语法。
1    class Coffees(tag: Tag) extends Table[(String, Double)](tag, “COFFEES”) {
2      def name = column[String](“COF_NAME”, O.PrimaryKey)
3      def price = column[Double](“PRICE”)
4      def * = (name, price)
5    }
6    val coffees = TableQuery[Coffees]

数据访问接口类型Scala的集合类型
1    // Query that only returns the “name” column
2    coffees.map(_.name)
3
4    // Query that does a “where price < 10.0″
5    coffees.filter(_.price < 10.0)

类型安全
你使用的IDE可以帮助你写代码
在编译时而无需到运行时就可以发现一些错误
1    // The result of “select PRICE from COFFEES” is a Seq of Double
2    // because of the type safe column definitions
3    val coffeeNames: Seq[Double] = coffees.map(_.price).list
4
5    // Query builders are type safe:
6    coffees.filter(_.price < 10.0)
7    // Using a string in the filter would result in a compilation error

可以组合
查询接口为函数,这些函数可以多次组合和重用。
1    // Create a query for coffee names with a price less than 10, sorted by name
2    coffees.filter(_.price < 10.0).sortBy(_.name).map(_.name)
3    // The generated SQL is equivalent to:
4    // select name from COFFEES where PRICE < 10.0 order by NAME

支持的数据库系统

  • DB2 (via slick-extensions)
  • Derby/JavaDB
  • H2
  • HSQLDB/HyperSQL
  • Microsoft Access
  • Microsoft SQL Server (via slick-extensions)
  • MySQL
  • Oracle (via slick-extensions)
  • PostgreSQL
  • SQLite

对于其它的一些数据库类型Slick也提供了有限的支持。

查询接口Lifted Embedding
Sclick 使用Lifted Embedding作为标准的数据库查询接口,此外Direct Embedding接口正在开发测试当中。
Lifted Embedding的名称来自于,你不是使用标准的Scala数据类型来访问查询数据库,而是使用Rep构造器来提升(Lift)Scala的基本数据类型,然后使用提升后的数据类

型来访问数据库,比如标准的Scala集合的例子:
1    case class Coffee(name: String, price: Double)
2    val coffees: List[Coffee] = //…
3
4    val l = coffees.filter(_.price > 8.0).map(_.name)
5    //                       ^       ^          ^
6    //                       Double  Double     String

而对应的提升之后的例子:
1    class Coffees(tag: Tag) extends Table[(String, Double)](tag, “COFFEES”) {
2      def name = column[String](“COF_NAME”)
3      def price = column[Double](“PRICE”)
4      def * = (name, price)
5    }
6    val coffees = TableQuery[Coffees]
7
8    val q = coffees.filter(_.price > 8.0).map(_.name)
9    //                       ^       ^          ^
10    //               Rep[Double]  Rep[Double]  Rep[String]

所有的基本Scala类型,都提升为Rep。即使是8.0字面量也被提升为Rep[Double]类型。
后面的例子,我们会采用Chinook数据库作为例子。

Chinook 数据库模型。

Chinook数据库前身为著名的Northwind数据库,它的数据模型如下:

ChinookDatabaseSchema1.1

 

Slick 编程(2): 准备开发环境

本篇介绍如果设置使用Slick的Scala开发环境,这里我们使用SBT命令行,SBT使用的目录结构和Maven一样,我们可以创建一个目录,比如Slick,然后创建如下的缺省目录结构:

src
main
java
resources
scala
test
java
resources
scala

因为我们打算使用MySQL数据库,并使用Slick来访问数据库,因此我们在Slick的根目录下创建一个build.sbt,添加相关引用:
1    name := “Scala Slick Examples”
2
3    version := “1.0”
4
5    scalaVersion := “2.10.4”
6
7    libraryDependencies += “com.typesafe.slick” %% “slick” % “2.0.2”
8
9    libraryDependencies += “org.slf4j” % “slf4j-nop” % “1.6.4”
10
11    libraryDependencies += “mysql” % “mysql-connector-java” % “5.1.18”

Slick使用SLF4J 作为日志库文件。
我们的MySQL数据库 Chinook 安装在本地服务器上面,我们在使用Slick可以手工创建数据库表Schema的定义,也可以使用自动代码生成工具从已有的数据库创建Table的Schema定义。
我们在命令行输入 sbt ,进入SBT控制台。
然后我们使用console,进入Scala控制台,注意此时SBT自动把build.sbt中引用到的库比如slick, mysql添加到Scala控制台,我们使用如下命令:
1    scala.slick.model.codegen.SourceCodeGenerator.main(
2      Array(slickDriver, jdbcDriver, url, outputFolder, pkg, user, password)
3    )

相关参数如下:
slickDriver Fully qualified name of Slick driver class, e.g. “scala.slick.driver.H2Driver”
jdbcDriver Fully qualified name of jdbc driver class, e.g. “org.h2.Driver”
url jdbc url, e.g. “jdbc:postgresql://localhost/test”
outputFolder Place where the package folder structure should be put
pkg Scala package the generated code should be places in
user database connection user name
password database connection password

例如对于本例,我们使用mysql数据库,可以在命令行输入如下命令:注意修改你的用户名和密码:
1    scala.slick.model.codegen.SourceCodeGenerator.main(
2      Array(“scala.slick.driver.MySQLDriver”, “com.mysql.jdbc.Driver”,
3      “jdbc:mysql://127.0.0.1/Chinook”,
4      “./src/main/scala”,
5      “com.guidebee.slick.example”, “user”, “password”)
6    )

这样自动代码生成工具,就在/src/main/scala目录下生成了Tables.scala文件
1    package com.guidebee.slick.example
2    // AUTO-GENERATED Slick data model
3    /** Stand-alone Slick data model for immediate use */
4    object Tables extends {
5      val profile = scala.slick.driver.MySQLDriver
6    } with Tables
7
8    /** Slick data model trait for extension, choice of backend or usage in the cake pattern. (Make sure to initialize this late.) */
9    trait Tables {
10      val profile: scala.slick.driver.JdbcProfile
11      import profile.simple._
12      import scala.slick.model.ForeignKeyAction
13      // NOTE: GetResult mappers for plain SQL are only generated for tables where Slick knows how to map the types of all columns.
14      import scala.slick.jdbc.{GetResult => GR}
15
16      /** DDL for all tables. Call .create to execute. */
17      lazy val ddl = Album.ddl ++ Artist.ddl ++ Customer.ddl ++ Employee.ddl ++ Genre.ddl ++ Invoice.ddl ++ Invoiceline.ddl ++ Mediatype.ddl ++ Playlist.ddl ++ Playlisttrack.ddl ++ Track.ddl
18
19      /** Entity class storing rows of table Album
20       *  @param albumid Database column AlbumId PrimaryKey
21       *  @param title Database column Title
22       *  @param artistid Database column ArtistId  */
23      case class AlbumRow(albumid: Int, title: String, artistid: Int)
24      /** GetResult implicit for fetching AlbumRow objects using plain SQL queries */
25      implicit def GetResultAlbumRow(implicit e0: GR[Int], e1: GR[String]):GR[AlbumRow] = GR{
26        prs => import prs._
27        AlbumRow.tupled((<<[Int], <<[String], <<[Int]))
28      }
29      /** Table description of table Album. Objects of this class serve as prototypes for rows in queries. */
30      class Album(tag: Tag) extends Table[AlbumRow](tag, “Album”) {
31        def * = (albumid, title, artistid) <> (AlbumRow.tupled, AlbumRow.unapply)
32        /** Maps whole row to an option. Useful for outer joins. */
33        def ? = (albumid.?, title.?, artistid.?).shaped.<>({r=>import r._;_1.map(_=> AlbumRow.tupled((_1.get, _2.get, _3.get)))}, (_:Any) => throw new Exception(“Inserting into ? projection not supported.”))
34
35        /** Database column AlbumId PrimaryKey */
36        val albumid: Column[Int] = column[Int](“AlbumId”, O.PrimaryKey)
37        /** Database column Title  */
38        val title: Column[String] = column[String](“Title”)
39        /** Database column ArtistId  */
40        val artistid: Column[Int] = column[Int](“ArtistId”)
41
42        /** Foreign key referencing Artist (database name FK_AlbumArtistId) */
43        lazy val artistFk = foreignKey(“FK_AlbumArtistId”, artistid, Artist)(r => r.artistid, onUpdate=ForeignKeyAction.NoAction, onDelete=ForeignKeyAction.NoAction)
44      }
45      /** Collection-like TableQuery object for table Album */
46      lazy val Album = new TableQuery(tag => new Album(tag))
47
48      /** Entity class storing rows of table Artist
49       *  @param artistid Database column ArtistId PrimaryKey
50       *  @param name Database column Name  */
51      case class ArtistRow(artistid: Int, name: Option[String])
52      /** GetResult implicit for fetching ArtistRow objects using plain SQL queries */
53      implicit def GetResultArtistRow(implicit e0: GR[Int], e1:GR[Option[String]]): GR[ArtistRow] = GR{
54        prs => import prs._
55        ArtistRow.tupled((<<[Int], <<?[String]))
56      }
57      /** Table description of table Artist. Objects of this class serve as prototypes for rows in queries. */
58      class Artist(tag: Tag) extends Table[ArtistRow](tag, “Artist”) {
59        def * = (artistid, name) <> (ArtistRow.tupled, ArtistRow.unapply)
60        /** Maps whole row to an option. Useful for outer joins. */
61        def ? = (artistid.?, name).shaped.<>({r=>import r._; _1.map(_=> ArtistRow.tupled((_1.get, _2)))}, (_:Any) =>  throw newException(“Inserting into ? projection not supported.”))
62
63        /** Database column ArtistId PrimaryKey */
64        val artistid: Column[Int] = column[Int](“ArtistId”, O.PrimaryKey)
65        /** Database column Name  */
66        val name: Column[Option[String]] = column[Option[String]](“Name”)
67      }
68      /** Collection-like TableQuery object for table Artist */
69      lazy val Artist = new TableQuery(tag => new Artist(tag))
70
71      /** Entity class storing rows of table Customer
72       *  @param customerid Database column CustomerId PrimaryKey
73       *  @param firstname Database column FirstName
74       *  @param lastname Database column LastName
75       *  @param company Database column Company
76       *  @param address Database column Address
77       *  @param city Database column City
78       *  @param state Database column State
79       *  @param country Database column Country
80       *  @param postalcode Database column PostalCode
81       *  @param phone Database column Phone
82       *  @param fax Database column Fax
83       *  @param email Database column Email
84       *  @param supportrepid Database column SupportRepId  */
85      case class CustomerRow(customerid: Int, firstname: String, lastname:String, company: Option[String], address: Option[String], city:Option[String], state: Option[String], country: Option[String], postalcode: Option[String], phone: Option[String], fax: Option[String], email: String, supportrepid: Option[Int])
86      /** GetResult implicit for fetching CustomerRow objects using plain SQL queries */
87      implicit def GetResultCustomerRow(implicit e0: GR[Int], e1:GR[String], e2: GR[Option[String]], e3: GR[Option[Int]]):GR[CustomerRow] = GR{
88        prs => import prs._
89        CustomerRow.tupled((<<[Int], <<[String], <<[String], <<?[String], <<?[String], <<?[String], <<?[String], <<?[String], <<?[String], <<?[String], <<?[String], <<[String], <<?[Int]))
90      }
91      /** Table description of table Customer. Objects of this class serve as prototypes for rows in queries. */
92      class Customer(tag: Tag) extends Table[CustomerRow](tag, “Customer”) {
93        def * = (customerid, firstname, lastname, company, address, city, state, country, postalcode, phone, fax, email, supportrepid) <> (CustomerRow.tupled, CustomerRow.unapply)
94        /** Maps whole row to an option. Useful for outer joins. */
95        def ? = (customerid.?, firstname.?, lastname.?, company, address, city, state, country, postalcode, phone, fax, email.?, supportrepid).shaped.<>({r=>import r._; _1.map(_=> CustomerRow.tupled((_1.get, _2.get, _3.get, _4, _5, _6, _7, _8, _9,_10, _11, _12.get, _13)))}, (_:Any) =>  throw new Exception(“Inserting into ? projection not supported.”))
96
97        /** Database column CustomerId PrimaryKey */
98        val customerid: Column[Int] = column[Int](“CustomerId”, O.PrimaryKey)
99        /** Database column FirstName  */
100        val firstname: Column[String] = column[String](“FirstName”)
101        /** Database column LastName  */
102        val lastname: Column[String] = column[String](“LastName”)
103        /** Database column Company  */
104        val company: Column[Option[String]] = column[Option[String]](“Company”)
105        /** Database column Address  */
106        val address: Column[Option[String]] = column[Option[String]](“Address”)
107        /** Database column City  */
108        val city: Column[Option[String]] = column[Option[String]](“City”)
109        /** Database column State  */
110        val state: Column[Option[String]] = column[Option[String]](“State”)
111        /** Database column Country  */
112        val country: Column[Option[String]] = column[Option[String]](“Country”)
113        /** Database column PostalCode  */
114        val postalcode: Column[Option[String]] = column[Option[String]](“PostalCode”)
115        /** Database column Phone  */
116        val phone: Column[Option[String]] = column[Option[String]](“Phone”)
117        /** Database column Fax  */
118        val fax: Column[Option[String]] = column[Option[String]](“Fax”)
119        /** Database column Email  */
120        val email: Column[String] = column[String](“Email”)
121        /** Database column SupportRepId  */
122        val supportrepid: Column[Option[Int]] = column[Option[Int]](“SupportRepId”)
123
124        /** Foreign key referencing Employee (database name FK_CustomerSupportRepId) */
125        lazy val employeeFk = foreignKey(“FK_CustomerSupportRepId”, supportrepid, Employee)(r => r.employeeid, onUpdate=ForeignKeyAction.NoAction, onDelete=ForeignKeyAction.NoAction)
126      }
127      /** Collection-like TableQuery object for table Customer */
128      lazy val Customer = new TableQuery(tag => new Customer(tag))
129
130      /** Entity class storing rows of table Employee
131       *  @param employeeid Database column EmployeeId PrimaryKey
132       *  @param lastname Database column LastName
133       *  @param firstname Database column FirstName
134       *  @param title Database column Title
135       *  @param reportsto Database column ReportsTo
136       *  @param birthdate Database column BirthDate
137       *  @param hiredate Database column HireDate
138       *  @param address Database column Address
139       *  @param city Database column City
140       *  @param state Database column State
141       *  @param country Database column Country
142       *  @param postalcode Database column PostalCode
143       *  @param phone Database column Phone
144       *  @param fax Database column Fax
145       *  @param email Database column Email  */
146      case class EmployeeRow(employeeid: Int, lastname: String, firstname:String, title: Option[String], reportsto: Option[Int], birthdate:Option1, hiredate: Option1, address: Option[String], city:Option[String], state: Option[String], country: Option[String], postalcode: Option[String], phone: Option[String], fax: Option[String], email: Option[String])
147      /** GetResult implicit for fetching EmployeeRow objects using plain SQL queries */
148      implicit def GetResultEmployeeRow(implicit e0: GR[Int], e1:GR[String], e2: GR[Option[String]], e3: GR[Option[Int]], e4:GR[Option1]): GR[EmployeeRow] = GR{
149        prs => import prs._
150        EmployeeRow.tupled((<<[Int], <<[String], <<[String], <<?[String], <<?[Int], <<?1, <<?1, <<?[String], <<?[String], <<?[String], <<?[String], <<?[String], <<?[String], <<?[String], <<?[String]))
151      }
152      /** Table description of table Employee. Objects of this class serve as prototypes for rows in queries. */
153      class Employee(tag: Tag) extends Table[EmployeeRow](tag, “Employee”) {
154        def * = (employeeid, lastname, firstname, title, reportsto, birthdate, hiredate, address, city, state, country, postalcode, phone, fax, email) <> (EmployeeRow.tupled, EmployeeRow.unapply)
155        /** Maps whole row to an option. Useful for outer joins. */
156        def ? = (employeeid.?, lastname.?, firstname.?, title, reportsto, birthdate, hiredate, address, city, state, country, postalcode, phone, fax, email).shaped.<>({r=>import r._; _1.map(_=> EmployeeRow.tupled((_1.get, _2.get, _3.get, _4, _5, _6, _7, _8, _9,_10, _11, _12, _13, _14, _15)))}, (_:Any) =>  throw newException(“Inserting into ? projection not supported.”))
157
158        /** Database column EmployeeId PrimaryKey */
159        val employeeid: Column[Int] = column[Int](“EmployeeId”, O.PrimaryKey)
160        /** Database column LastName  */
161        val lastname: Column[String] = column[String](“LastName”)
162        /** Database column FirstName  */
163        val firstname: Column[String] = column[String](“FirstName”)
164        /** Database column Title  */
165        val title: Column[Option[String]] = column[Option[String]](“Title”)
166        /** Database column ReportsTo  */
167        val reportsto: Column[Option[Int]] = column[Option[Int]](“ReportsTo”)
168        /** Database column BirthDate  */
169        val birthdate: Column[Option1] = column[Option1](“BirthDate”)
170        /** Database column HireDate  */
171        val hiredate: Column[Option1] = column[Option1](“HireDate”)
172        /** Database column Address  */
173        val address: Column[Option[String]] = column[Option[String]](“Address”)
174        /** Database column City  */
175        val city: Column[Option[String]] = column[Option[String]](“City”)
176        /** Database column State  */
177        val state: Column[Option[String]] = column[Option[String]](“State”)
178        /** Database column Country  */
179        val country: Column[Option[String]] = column[Option[String]](“Country”)
180        /** Database column PostalCode  */
181        val postalcode: Column[Option[String]] = column[Option[String]](“PostalCode”)
182        /** Database column Phone  */
183        val phone: Column[Option[String]] = column[Option[String]](“Phone”)
184        /** Database column Fax  */
185        val fax: Column[Option[String]] = column[Option[String]](“Fax”)
186        /** Database column Email  */
187        val email: Column[Option[String]] = column[Option[String]](“Email”)
188
189        /** Foreign key referencing Employee (database name FK_EmployeeReportsTo) */
190        lazy val employeeFk = foreignKey(“FK_EmployeeReportsTo”, reportsto, Employee)(r => r.employeeid, onUpdate=ForeignKeyAction.NoAction, onDelete=ForeignKeyAction.NoAction)
191      }
192      /** Collection-like TableQuery object for table Employee */
193      lazy val Employee = new TableQuery(tag => new Employee(tag))
194
195      /** Entity class storing rows of table Genre
196       *  @param genreid Database column GenreId PrimaryKey
197       *  @param name Database column Name  */
198      case class GenreRow(genreid: Int, name: Option[String])
199      /** GetResult implicit for fetching GenreRow objects using plain SQL queries */
200      implicit def GetResultGenreRow(implicit e0: GR[Int], e1:GR[Option[String]]): GR[GenreRow] = GR{
201        prs => import prs._
202        GenreRow.tupled((<<[Int], <<?[String]))
203      }
204      /** Table description of table Genre. Objects of this class serve as prototypes for rows in queries. */
205      class Genre(tag: Tag) extends Table[GenreRow](tag, “Genre”) {
206        def * = (genreid, name) <> (GenreRow.tupled, GenreRow.unapply)
207        /** Maps whole row to an option. Useful for outer joins. */
208        def ? = (genreid.?, name).shaped.<>({r=>import r._; _1.map(_=> GenreRow.tupled((_1.get, _2)))}, (_:Any) =>  throw newException(“Inserting into ? projection not supported.”))
209
210        /** Database column GenreId PrimaryKey */
211        val genreid: Column[Int] = column[Int](“GenreId”, O.PrimaryKey)
212        /** Database column Name  */
213        val name: Column[Option[String]] = column[Option[String]](“Name”)
214      }
215      /** Collection-like TableQuery object for table Genre */
216      lazy val Genre = new TableQuery(tag => new Genre(tag))
217
218      /** Entity class storing rows of table Invoice
219       *  @param invoiceid Database column InvoiceId PrimaryKey
220       *  @param customerid Database column CustomerId
221       *  @param invoicedate Database column InvoiceDate
222       *  @param billingaddress Database column BillingAddress
223       *  @param billingcity Database column BillingCity
224       *  @param billingstate Database column BillingState
225       *  @param billingcountry Database column BillingCountry
226       *  @param billingpostalcode Database column BillingPostalCode
227       *  @param total Database column Total  */
228      case class InvoiceRow(invoiceid: Int, customerid: Int, invoicedate:java.sql.Timestamp, billingaddress: Option[String], billingcity:Option[String], billingstate: Option[String], billingcountry:Option[String], billingpostalcode: Option[String], total:scala.math.BigDecimal)
229      /** GetResult implicit for fetching InvoiceRow objects using plain SQL queries */
230      implicit def GetResultInvoiceRow(implicit e0: GR[Int], e1: GR1, e2:GR[Option[String]], e3: GR1): GR[InvoiceRow] = GR{
231        prs => import prs._
232        InvoiceRow.tupled((<<[Int], <<[Int], <<1, <<?[String], <<?[String], <<?[String], <<?[String], <<?[String], <<1))
233      }
234      /** Table description of table Invoice. Objects of this class serve as prototypes for rows in queries. */
235      class Invoice(tag: Tag) extends Table[InvoiceRow](tag, “Invoice”) {
236        def * = (invoiceid, customerid, invoicedate, billingaddress, billingcity, billingstate, billingcountry, billingpostalcode, total) <> (InvoiceRow.tupled, InvoiceRow.unapply)
237        /** Maps whole row to an option. Useful for outer joins. */
238        def ? = (invoiceid.?, customerid.?, invoicedate.?, billingaddress, billingcity, billingstate, billingcountry, billingpostalcode, total.?).shaped.<>({r=>import r._; _1.map(_=> InvoiceRow.tupled((_1.get, _2.get, _3.get, _4, _5, _6, _7, _8,_9.get)))}, (_:Any) =>  throw new Exception(“Inserting into ? projection not supported.”))
239
240        /** Database column InvoiceId PrimaryKey */
241        val invoiceid: Column[Int] = column[Int](“InvoiceId”, O.PrimaryKey)
242        /** Database column CustomerId  */
243        val customerid: Column[Int] = column[Int](“CustomerId”)
244        /** Database column InvoiceDate  */
245        val invoicedate: Column1 = column1(“InvoiceDate”)
246        /** Database column BillingAddress  */
247        val billingaddress: Column[Option[String]] = column[Option[String]](“BillingAddress”)
248        /** Database column BillingCity  */
249        val billingcity: Column[Option[String]] = column[Option[String]](“BillingCity”)
250        /** Database column BillingState  */
251        val billingstate: Column[Option[String]] = column[Option[String]](“BillingState”)
252        /** Database column BillingCountry  */
253        val billingcountry: Column[Option[String]] = column[Option[String]](“BillingCountry”)
254        /** Database column BillingPostalCode  */
255        val billingpostalcode: Column[Option[String]] =column[Option[String]](“BillingPostalCode”)
256        /** Database column Total  */
257        val total: Column1 = column1(“Total”)
258
259        /** Foreign key referencing Customer (database name FK_InvoiceCustomerId) */
260        lazy val customerFk = foreignKey(“FK_InvoiceCustomerId”, customerid, Customer)(r => r.customerid, onUpdate=ForeignKeyAction.NoAction, onDelete=ForeignKeyAction.NoAction)
261      }
262      /** Collection-like TableQuery object for table Invoice */
263      lazy val Invoice = new TableQuery(tag => new Invoice(tag))
264
265      /** Entity class storing rows of table Invoiceline
266       *  @param invoicelineid Database column InvoiceLineId PrimaryKey
267       *  @param invoiceid Database column InvoiceId
268       *  @param trackid Database column TrackId
269       *  @param unitprice Database column UnitPrice
270       *  @param quantity Database column Quantity  */
271      case class InvoicelineRow(invoicelineid: Int, invoiceid: Int, trackid: Int, unitprice: scala.math.BigDecimal, quantity: Int)
272      /** GetResult implicit for fetching InvoicelineRow objects using plain SQL queries */
273      implicit def GetResultInvoicelineRow(implicit e0: GR[Int], e1: GR1):GR[InvoicelineRow] = GR{
274        prs => import prs._
275        InvoicelineRow.tupled((<<[Int], <<[Int], <<[Int], <<1, <<[Int]))
276      }
277      /** Table description of table InvoiceLine. Objects of this class serve as prototypes for rows in queries. */
278      class Invoiceline(tag: Tag) extends Table[InvoicelineRow](tag,”InvoiceLine”) {
279        def * = (invoicelineid, invoiceid, trackid, unitprice, quantity) <> (InvoicelineRow.tupled, InvoicelineRow.unapply)
280        /** Maps whole row to an option. Useful for outer joins. */
281        def ? = (invoicelineid.?, invoiceid.?, trackid.?, unitprice.?, quantity.?).shaped.<>({r=>import r._; _1.map(_=> InvoicelineRow.tupled((_1.get, _2.get, _3.get, _4.get, _5.get)))}, (_:Any) =>  throw new Exception(“Inserting into ? projection not supported.”))
282
283        /** Database column InvoiceLineId PrimaryKey */
284        val invoicelineid: Column[Int] = column[Int](“InvoiceLineId”, O.PrimaryKey)
285        /** Database column InvoiceId  */
286        val invoiceid: Column[Int] = column[Int](“InvoiceId”)
287        /** Database column TrackId  */
288        val trackid: Column[Int] = column[Int](“TrackId”)
289        /** Database column UnitPrice  */
290        val unitprice: Column1 = column1(“UnitPrice”)
291        /** Database column Quantity  */
292        val quantity: Column[Int] = column[Int](“Quantity”)
293
294        /** Foreign key referencing Invoice (database name FK_InvoiceLineInvoiceId) */
295        lazy val invoiceFk = foreignKey(“FK_InvoiceLineInvoiceId”, invoiceid, Invoice)(r => r.invoiceid, onUpdate=ForeignKeyAction.NoAction, onDelete=ForeignKeyAction.NoAction)
296        /** Foreign key referencing Track (database name FK_InvoiceLineTrackId) */
297        lazy val trackFk = foreignKey(“FK_InvoiceLineTrackId”, trackid, Track)(r => r.trackid, onUpdate=ForeignKeyAction.NoAction, onDelete=ForeignKeyAction.NoAction)
298      }
299      /** Collection-like TableQuery object for table Invoiceline */
300      lazy val Invoiceline = new TableQuery(tag => new Invoiceline(tag))
301
302      /** Entity class storing rows of table Mediatype
303       *  @param mediatypeid Database column MediaTypeId PrimaryKey
304       *  @param name Database column Name  */
305      case class MediatypeRow(mediatypeid: Int, name: Option[String])
306      /** GetResult implicit for fetching MediatypeRow objects using plain SQL queries */
307      implicit def GetResultMediatypeRow(implicit e0: GR[Int], e1:GR[Option[String]]): GR[MediatypeRow] = GR{
308        prs => import prs._
309        MediatypeRow.tupled((<<[Int], <<?[String]))
310      }
311      /** Table description of table MediaType. Objects of this class serve as prototypes for rows in queries. */
312      class Mediatype(tag: Tag) extends Table[MediatypeRow](tag,”MediaType”) {
313        def * = (mediatypeid, name) <> (MediatypeRow.tupled, MediatypeRow.unapply)
314        /** Maps whole row to an option. Useful for outer joins. */
315        def ? = (mediatypeid.?, name).shaped.<>({r=>import r._; _1.map(_=> MediatypeRow.tupled((_1.get, _2)))}, (_:Any) =>  throw newException(“Inserting into ? projection not supported.”))
316
317        /** Database column MediaTypeId PrimaryKey */
318        val mediatypeid: Column[Int] = column[Int](“MediaTypeId”, O.PrimaryKey)
319        /** Database column Name  */
320        val name: Column[Option[String]] = column[Option[String]](“Name”)
321      }
322      /** Collection-like TableQuery object for table Mediatype */
323      lazy val Mediatype = new TableQuery(tag => new Mediatype(tag))
324
325      /** Entity class storing rows of table Playlist
326       *  @param playlistid Database column PlaylistId PrimaryKey
327       *  @param name Database column Name  */
328      case class PlaylistRow(playlistid: Int, name: Option[String])
329      /** GetResult implicit for fetching PlaylistRow objects using plain SQL queries */
330      implicit def GetResultPlaylistRow(implicit e0: GR[Int], e1:GR[Option[String]]): GR[PlaylistRow] = GR{
331        prs => import prs._
332        PlaylistRow.tupled((<<[Int], <<?[String]))
333      }
334      /** Table description of table Playlist. Objects of this class serve as prototypes for rows in queries. */
335      class Playlist(tag: Tag) extends Table[PlaylistRow](tag, “Playlist”) {
336        def * = (playlistid, name) <> (PlaylistRow.tupled, PlaylistRow.unapply)
337        /** Maps whole row to an option. Useful for outer joins. */
338        def ? = (playlistid.?, name).shaped.<>({r=>import r._; _1.map(_=> PlaylistRow.tupled((_1.get, _2)))}, (_:Any) =>  throw newException(“Inserting into ? projection not supported.”))
339
340        /** Database column PlaylistId PrimaryKey */
341        val playlistid: Column[Int] = column[Int](“PlaylistId”, O.PrimaryKey)
342        /** Database column Name  */
343        val name: Column[Option[String]] = column[Option[String]](“Name”)
344      }
345      /** Collection-like TableQuery object for table Playlist */
346      lazy val Playlist = new TableQuery(tag => new Playlist(tag))
347
348      /** Entity class storing rows of table Playlisttrack
349       *  @param playlistid Database column PlaylistId
350       *  @param trackid Database column TrackId  */
351      case class PlaylisttrackRow(playlistid: Int, trackid: Int)
352      /** GetResult implicit for fetching PlaylisttrackRow objects using plain SQL queries */
353      implicit def GetResultPlaylisttrackRow(implicit e0: GR[Int]):GR[PlaylisttrackRow] = GR{
354        prs => import prs._
355        PlaylisttrackRow.tupled((<<[Int], <<[Int]))
356      }
357      /** Table description of table PlaylistTrack. Objects of this class serve as prototypes for rows in queries. */
358      class Playlisttrack(tag: Tag) extends Table[PlaylisttrackRow](tag,”PlaylistTrack”) {
359        def * = (playlistid, trackid) <> (PlaylisttrackRow.tupled, PlaylisttrackRow.unapply)
360        /** Maps whole row to an option. Useful for outer joins. */
361        def ? = (playlistid.?, trackid.?).shaped.<>({r=>import r._;_1.map(_=> PlaylisttrackRow.tupled((_1.get, _2.get)))}, (_:Any) => throw new Exception(“Inserting into ? projection not supported.”))
362
363        /** Database column PlaylistId  */
364        val playlistid: Column[Int] = column[Int](“PlaylistId”)
365        /** Database column TrackId  */
366        val trackid: Column[Int] = column[Int](“TrackId”)
367
368        /** Primary key of Playlisttrack (database name PlaylistTrack_PK) */
369        val pk = primaryKey(“PlaylistTrack_PK”, (playlistid, trackid))
370
371        /** Foreign key referencing Playlist (database name FK_PlaylistTrackPlaylistId) */
372        lazy val playlistFk = foreignKey(“FK_PlaylistTrackPlaylistId”, playlistid, Playlist)(r => r.playlistid, onUpdate=ForeignKeyAction.NoAction, onDelete=ForeignKeyAction.NoAction)
373        /** Foreign key referencing Track (database name FK_PlaylistTrackTrackId) */
374        lazy val trackFk = foreignKey(“FK_PlaylistTrackTrackId”, trackid, Track)(r => r.trackid, onUpdate=ForeignKeyAction.NoAction, onDelete=ForeignKeyAction.NoAction)
375      }
376      /** Collection-like TableQuery object for table Playlisttrack */
377      lazy val Playlisttrack = new TableQuery(tag => newPlaylisttrack(tag))
378
379      /** Entity class storing rows of table Track
380       *  @param trackid Database column TrackId PrimaryKey
381       *  @param name Database column Name
382       *  @param albumid Database column AlbumId
383       *  @param mediatypeid Database column MediaTypeId
384       *  @param genreid Database column GenreId
385       *  @param composer Database column Composer
386       *  @param milliseconds Database column Milliseconds
387       *  @param bytes Database column Bytes
388       *  @param unitprice Database column UnitPrice  */
389      case class TrackRow(trackid: Int, name: String, albumid: Option[Int], mediatypeid: Int, genreid: Option[Int], composer: Option[String], milliseconds: Int, bytes: Option[Int], unitprice:scala.math.BigDecimal)
390      /** GetResult implicit for fetching TrackRow objects using plain SQL queries */
391      implicit def GetResultTrackRow(implicit e0: GR[Int], e1: GR[String], e2: GR[Option[Int]], e3: GR[Option[String]], e4: GR1): GR[TrackRow] =GR{
392        prs => import prs._
393        TrackRow.tupled((<<[Int], <<[String], <<?[Int], <<[Int], <<?[Int], <<?[String], <<[Int], <<?[Int], <<1))
394      }
395      /** Table description of table Track. Objects of this class serve as prototypes for rows in queries. */
396      class Track(tag: Tag) extends Table[TrackRow](tag, “Track”) {
397        def * = (trackid, name, albumid, mediatypeid, genreid, composer, milliseconds, bytes, unitprice) <> (TrackRow.tupled, TrackRow.unapply)
398        /** Maps whole row to an option. Useful for outer joins. */
399        def ? = (trackid.?, name.?, albumid, mediatypeid.?, genreid, composer, milliseconds.?, bytes, unitprice.?).shaped.<>({r=>import r._;_1.map(_=> TrackRow.tupled((_1.get, _2.get, _3, _4.get, _5, _6, _7.get,_8, _9.get)))}, (_:Any) =>  throw new Exception(“Inserting into ? projection not supported.”))
400
401        /** Database column TrackId PrimaryKey */
402        val trackid: Column[Int] = column[Int](“TrackId”, O.PrimaryKey)
403        /** Database column Name  */
404        val name: Column[String] = column[String](“Name”)
405        /** Database column AlbumId  */
406        val albumid: Column[Option[Int]] = column[Option[Int]](“AlbumId”)
407        /** Database column MediaTypeId  */
408        val mediatypeid: Column[Int] = column[Int](“MediaTypeId”)
409        /** Database column GenreId  */
410        val genreid: Column[Option[Int]] = column[Option[Int]](“GenreId”)
411        /** Database column Composer  */
412        val composer: Column[Option[String]] = column[Option[String]](“Composer”)
413        /** Database column Milliseconds  */
414        val milliseconds: Column[Int] = column[Int](“Milliseconds”)
415        /** Database column Bytes  */
416        val bytes: Column[Option[Int]] = column[Option[Int]](“Bytes”)
417        /** Database column UnitPrice  */
418        val unitprice: Column1 = column1(“UnitPrice”)
419
420        /** Foreign key referencing Album (database name FK_TrackAlbumId) */
421        lazy val albumFk = foreignKey(“FK_TrackAlbumId”, albumid, Album)(r=> r.albumid, onUpdate=ForeignKeyAction.NoAction, onDelete=ForeignKeyAction.NoAction)
422        /** Foreign key referencing Genre (database name FK_TrackGenreId) */
423        lazy val genreFk = foreignKey(“FK_TrackGenreId”, genreid, Genre)(r=> r.genreid, onUpdate=ForeignKeyAction.NoAction, onDelete=ForeignKeyAction.NoAction)
424        /** Foreign key referencing Mediatype (database name FK_TrackMediaTypeId) */
425        lazy val mediatypeFk = foreignKey(“FK_TrackMediaTypeId”, mediatypeid, Mediatype)(r => r.mediatypeid, onUpdate=ForeignKeyAction.NoAction, onDelete=ForeignKeyAction.NoAction)
426      }
427      /** Collection-like TableQuery object for table Track */
428      lazy val Track = new TableQuery(tag => new Track(tag))
429    }

 

原文:http://www.scala-china.net/discuz/forum.php?mod=viewthread&tid=151252&extra=page%3D1



快乐成长 每天进步一点点