forked from chirino/play-scala
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SqlTests.scala
222 lines (178 loc) · 9.05 KB
/
SqlTests.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
import play.test._
import org.junit._
import org.scalatest.junit._
import org.scalatest._
import org.scalatest.matchers._
import play.db.anorm._
import SqlParser._
// Constructors with unspported type of parameter won't be picked
case class Task(ids:Option[List[Int]],comment:String){
def this(ids:Option[List[Int]])=this(ids,"no comment.")
def this(comment:String)=this(None,comment)
}
import Row._
object Task extends Magic[Task]
case class Student(id:String)
object Student extends Magic[Student]
class SqlTests extends UnitTestCase with ShouldMatchersForJUnit {
def meta(items:(String,(Boolean,Class[_]))*)=MetaData(items.toList.map(i=>MetaDataItem(i._1,i._2._1,i._2._2.getName)))
@Test def useTheMagicParser {
val metaData=meta("TASK.COMMENT"->(true,classOf[String]),
"TASK.NAME"->(false,classOf[String]))
val in= StreamReader(Stream.range(1,100).map(i => MockRow(List("comment no:"+i, "nameb"),metaData)))
commit((str("COMMENT1")))* (in) should be (Error(ColumnNotFound("COMMENT1").toString,in))
((str("COMMENT1")) ?)(in).get should be (None)
(str("COMMENT1"))+ (in) should be (Failure(ColumnNotFound("COMMENT1").toString,in))
(str("COMMENT"))* (in) should be (Success(List(),in))
str("TASK.COMMENT")+ (in) should be (
Failure(UnexpectedNullableFound("TASK.COMMENT").toString,in))
str("COMMENT")+ (in) should be (
Failure(UnexpectedNullableFound("TASK.COMMENT").toString,in))
import Magic._
Task* (in) should be(Success(List(),in))
(Task)+ (in) should be(
Failure(UnexpectedNullableFound("TASK.COMMENT").toString,in))
commit((Task)+) (in) should be(
Error(UnexpectedNullableFound("TASK.COMMENT").toString,in))
val metaData1=meta("TASK.COMMENT"->(false,classOf[String]),
"TASK.NAME"->(false,classOf[String]))
val in1= StreamReader(Stream.range(1,100).map(i => MockRow(List("comment no:"+i, "nameb"),metaData1)))
import Row._
commit((Task) +)(in1).get should be(
List.range(1,100).map(i=>new Task("comment no:"+i)))
}
@Test def testNullables {
import play.db.anorm.Row._
val metaData=meta("PERSON.ID"->(true,classOf[java.lang.Integer]))
val in= StreamReader(Stream.range(1,100).map(i=>MockRow(List( if(i % 2 ==0) i else null),metaData)))
println(commit((get[Option[Int]]("PERSON.ID")) +)(in) )
}
@Test def testNullInNonNullable {
import play.db.anorm.Row._
val metaData=meta("PERSON.ID"->(false,classOf[java.lang.Integer]))
val in= StreamReader(Stream.range(1,2).map(i=>MockRow(List(null),metaData)))
println(commit((get[Int]("PERSON.ID")) +)(in) )
}
@Test def useSqlParserForGroupBys {
val metaData=meta("PERSON.ID"->(false,classOf[Int]),
"PERSON.NAME"->(false,classOf[String]),
"PERSON.AGE"->(true,classOf[Int]),
"COMMENT.ID"->(false,classOf[Int]),
"COMMENT.TEXT"->(false,classOf[String]))
val in= Stream.range(1,100)
.flatMap(i =>
Stream.range(1,100)
.map(j =>
MockRow(List(i, "person"+i, 13, j, "comment"+j),metaData)))
// manual groupBy
val groupByPerson=spanM(by=int("PERSON.ID"),(str("COMMENT.TEXT")))* ;
groupByPerson(StreamReader(in)).get should be (
List.fill(99)(List.range(1,100).map("comment"+_)))
// "magical" groupBy
import Magic._
val parsePeople = Person ~< (Person spanM Comment) ^^
{case p ~ cs => p.copy(comments=cs) } *;
( parsePeople (StreamReader(in)) get ) should be (
List.range(1,100).map(
i=> Person(i, "person"+i, Seq.range(1,100).map(
j=> Comment(j,"comment"+j) ))))
}
@Test def useSomeMagicSql{
play.db.DB.execute("DROP TABLE IF EXISTS Task")
play.db.DB.execute("DROP TABLE IF EXISTS Student")
play.db.DB.execute("""CREATE TABLE Task
(Id char(60) NOT NULL,
Comment char(60) NOT NULL) """)
play.db.DB.execute("""CREATE TABLE Student
(Id char(60) NOT NULL,
Task_Id char(60) NOT NULL) """)
play.db.DB.execute("""insert into Task Values('1','some comment')""")
play.db.DB.execute("""insert into Student Values('1','1')""")
Task.find("where id={id}").on("id" -> 1).first() should be (Some(new Task("some comment")))
Task.find().list() should be (List(new Task("some comment")))
Task.find().list() should be (List(new Task("some comment")))
Task.find("where id={id}").on("id" -> 3).first() should be (None)
SQL("select * from Task join Student on Task.id=Student.Task_Id").as(Task ~< Student) should be (SqlParser.~(new Task("some comment"),Student("1")))
}
@Test def trySomeMagicSqlFailure{
play.db.DB.execute("DROP TABLE IF EXISTS Task")
play.db.DB.execute("DROP TABLE IF EXISTS Student")
play.db.DB.execute("""CREATE TABLE Task
(Id char(60) NOT NULL,
Comment1 char(60) NOT NULL) """)
play.db.DB.execute("""CREATE TABLE Student
(Id char(60) NOT NULL,
Task_Id char(60) NOT NULL) """)
play.db.DB.execute("""insert into Task Values('1','some comment')""")
play.db.DB.execute("""insert into Student Values('1','1')""")
val t = evaluating { Task.find("where id={id}").on("id" -> 1).first() } should produce [RuntimeException]
t.getMessage should equal ("ColumnNotFound(TASK.COMMENT)")
val thrown = evaluating { Task.find().list() } should produce [RuntimeException]
thrown.getMessage should equal ("ColumnNotFound(TASK.COMMENT)")
val thrown1 = evaluating {
SQL("select * from Task join Student on Task.id=Student.Task_Id")
.as(Task ~< Student)
} should produce [RuntimeException]
thrown1.getMessage should equal ("ColumnNotFound(TASK.COMMENT)")
}
@Test def testAlternate(){
play.db.DB.execute("DROP TABLE IF EXISTS Post")
play.db.DB.execute("""CREATE TABLE Post
(Id char(60) NOT NULL,
Type char(60) NOT NULL,
Title char(60) NOT NULL,
URL char(200) DEFAULT 'non' NOT Null,
Body char(360) DEFAULT 'non' NOT Null) """)
play.db.DB.execute("""insert into Post Values('1','Link','zengularity','http://www.zengularity.com','non')""")
play.db.DB.execute("""insert into Post Values('1','Text','Functional Web','non','It rocks!')""")
play.db.DB.execute("""insert into Post Values('1','Text','Functional Web','non','It rocks!')""")
import Row._
play.db.anorm.Sql.sql("select * from Post")
.as( 'TYPE.is("Text") ~> Text |
'TYPE.is("Link") ~> Link +) should be (
List(Link("1","zengularity","http://www.zengularity.com"),
Text("1","Functional Web","It rocks!"),
Text("1","Functional Web","It rocks!")))
}
@Test def insertAnEntity(){
play.db.DB.execute("DROP TABLE IF EXISTS User2")
play.db.DB.execute("""CREATE TABLE User2
(Id INTEGER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY ,
Address char(60) NOT NULL,
Name char(60) NOT NULL) """)
User2.create(User2(NotAssigned,"Paul","Address")).right.get should be (User2(Id(1),"Paul","Address"))
}
@Test def updateAnEntity(){
play.db.DB.execute("DROP TABLE IF EXISTS User2")
play.db.DB.execute("""CREATE TABLE User2
(Id INTEGER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY ,
Address char(60) NOT NULL,
Name char(60) NOT NULL) """)
val newUser:User2 = User2.create(User2(NotAssigned,"Paul","Address")).right.get
User2.update(newUser.copy(name="new name")) should be ()
}
@Test def count(){
play.db.DB.execute("DROP TABLE IF EXISTS User2")
play.db.DB.execute("""CREATE TABLE User2
(Id INTEGER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY ,
Address char(60) NOT NULL,
Name char(60) NOT NULL) """)
play.db.DB.execute("""insert into User2 (Address, Name) Values('address','Paul')""")
play.db.DB.execute("""insert into User2 (Address, Name) Values('address','Paul')""")
User2.count().single() should be (2)
}
}
case class User2(id:Pk[Long],name:String,address:String)
import Row._
object User2 extends Magic[User2]
abstract class Post
case class Link(id:String,title:String,url:String) extends Post
object Link extends Magic[Link](Some("POST"))
case class Text(id:String,title:String,body:String) extends Post
object Text extends Magic[Text](Some("POST"))
case class Person(id: Int,name:String,comments:Seq[Comment]) {
def this(id:Int,name:String)=this(id,name,List())
}
object Person extends Magic[Person]
case class Comment(id: Int,text:String)
object Comment extends Magic[Comment]