Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

slick & scala : What are TableQueries? [closed]

Tags:

scala

slick

I am a bit disappointed with slick & its TableQueries : the model of an application can be a "class Persons(tag: Tag) extends Table[Person] for example (where Person is a case class with some fields like name, age,address...). The weird point is the "val persons = TableQuery[Persons]" contains all the records.

To have for example all the adults, we can use:

adults = persons.filter(p => p.age >= 18).list()

Is the content of the database loaded in the variable persons? Is there on the contrary a mechanism that allows to evaluate not "persons" but "adults"?(a sort of lazy variable)? Can we say something like 'at any time, "persons" contains the entire database'?

Are there good practices, some important ideas that can help the developer?

thanks.

like image 746
lolveley Avatar asked Jan 24 '14 17:01

lolveley


1 Answers

You are mistaken in your assumption that persons contains all of the records. The Table and TableQuery classes are representations of a SQL table, and the whole point of the library is to ease the interaction with SQL databases by providing a convenient, scala-like syntax.

When you say

val adults = persons.filter{ p => p.age >= 18 }

You've essentially created a SQL query that you can think of as

SELECT * FROM PERSONS WHERE AGE >= 18

Then when you call .list() it executes that query, transforming the result rows from the database back into instances of your Person case class. Most of the methods that have anything to do with slick's Table or Query classes will be focused on generating Queries (i.e. "select" statements). They don't actually load any data until you invoke them (e.g. by calling .list() or .foreach).

As for good practices and important ideas, I'd suggest you read through their documentation, as well as take a look at the scaladocs for any of the classes you are curious about.

http://slick.typesafe.com/docs/

like image 194
Dylan Avatar answered Oct 02 '22 13:10

Dylan