ZivkicaI

SLICK

Dec 27th, 2019
687
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 8.04 KB | None | 0 0
  1. import scala.concurrent.{Await, Future}
  2. import scala.concurrent.ExecutionContext.Implicits.global
  3. import scala.concurrent.duration.Duration
  4. import slick.basic.DatabasePublisher
  5. import slick.dbio.Effect
  6. import slick.jdbc.H2Profile.api._
  7. import slick.lifted.QueryBase
  8. import slick.sql.FixedSqlAction
  9.  
  10. object HelloSlick1 extends App{
  11.   val zaFilter = RandomCaseClass(None,None)
  12.  
  13.   val db = Database.forConfig("h2mem1")
  14.   try {
  15.  
  16.     // The query interface for the Suppliers table
  17.     val suppliers: TableQuery[Suppliers] = TableQuery[Suppliers]
  18.  
  19.     // the query interface for the Coffees table
  20.     val coffees: TableQuery[Coffees] = TableQuery[Coffees]
  21.  
  22.     val setupAction: DBIO[Unit] = DBIO.seq(
  23.       // Create the schema by combining the DDLs for the Suppliers and Coffees
  24.       // tables using the query interfaces
  25.       (suppliers.schema ++ coffees.schema).create,
  26.  
  27.       // Insert some suppliers
  28.       suppliers += (101, "Acme, Inc.", "99 Market Street", "Groundsville", "CA", "95199"),
  29.       suppliers += ( 49, "Superior Coffee", "1 Party Place", "Mendocino", "CA", "95460"),
  30.       suppliers += (150, "The High Ground", "100 Coffee Lane", "Meadows", "CA", "93966")
  31.     )
  32.  
  33.     val setupFuture: Future[Unit] = db.run(setupAction)
  34.     val f = setupFuture.flatMap { _ =>
  35.  
  36.       // Insert some coffees (using JDBC's batch insert feature)
  37.       val insertAction:DBIO[Option[Int]]= coffees ++= Seq (
  38.         ("Colombian",         101, 7.99, 0, 0),
  39.         ("French_Roast",       49, 8.99, 0, 0),
  40.         ("Espresso",          150, 9.99, 0, 0),
  41.         ("Colombian_Decaf",   101, 8.99, 0, 0),
  42.         ("French_Roast_Decaf", 49, 9.99, 0, 0)
  43.       )
  44.  
  45.       db.run(insertAction)
  46.  
  47.     }.flatMap{ _ =>
  48.         println(suppliers.result.statements.mkString)
  49.       db.run(suppliers.result)
  50.     }.flatMap{ _ =>
  51.       val kveri: Query[Rep[String], String, Seq] = coffees.filter(cof=> cof.supID === 101).map(x=>x.name)
  52.       println(kveri.result.statements.mkString)
  53.       db.run(kveri.result)
  54.     }.flatMap { _ =>      //site kafinja da gi updatenam shto go sodrzat imeto Colombian so toa shto cenata kje im ja smenam UPDATE!!!
  55.  
  56.       val updateQuery = coffees.filter(_.name.like("Colombian%")).map(_.price)
  57.  
  58.       val updateAction: DBIO[Int] = updateQuery.update(9999)
  59.  
  60.       db.run(updateAction)
  61.  
  62.     }.flatMap{ _ =>
  63.  
  64.       val i = coffees
  65.  
  66.       db.run(i.result)
  67.  
  68.  
  69.     }.flatMap{ _ =>        //da gi izbrisham site kafinja na koi shto cenata im e 9999 DELETE!!!
  70.       val zaBrishenje = coffees.filter(_.price === 9999.0)
  71.  
  72.       val deleteAction: FixedSqlAction[Int, NoStream, Effect.Write] =zaBrishenje.delete
  73.       db.run(deleteAction)
  74.     }.flatMap{_ =>
  75.       val c= coffees
  76.       db.run(c.result)
  77.  
  78.     }.flatMap{ _ =>     // da dodadam ushte edno kafe vo kafinjata     INSERT!!!
  79.       val insertActions = DBIO.seq(
  80.         coffees += ("Bravo", 101, 99.99, 0, 0))
  81.  
  82.       db.run(insertActions)
  83.  
  84.     }.flatMap { _ =>
  85.  
  86.       db.run(coffees.result)
  87.  
  88.     }.flatMap { _ =>              //SO FOR JOIN DA NAPRAAM NA COFFEE I NA SUPPLIERS
  89.       val joinQuery = for {
  90.         (c,s) <- coffees join suppliers
  91.       } yield (c.name, s.name)
  92.  
  93.       db.run(joinQuery.result)
  94.     }.flatMap{ _ =>                //BEZ FOR JOIN NA COFFEE I NA SUPPLIERS I SAMO IMETO NA KAFETO DA GI ZEMAM I IMETO NA SUPPLIEROT
  95.       val q= coffees join suppliers on (_.supID === _.id)
  96.       val p=q.map{ case (kafe, suplier) =>
  97.         (kafe.name, suplier.name)
  98.       }
  99.  
  100.       db.run(p.result)
  101.     }
  102.    
  103.  
  104.       /*.flatMap { _ =>
  105.  
  106.         /* Streaming */
  107.  
  108.         val coffeeNamesAction: StreamingDBIO[Seq[String], String] =
  109.           coffees.map(_.name).result
  110.  
  111.         val coffeeNamesPublisher: DatabasePublisher[String] =
  112.           db.stream(coffeeNamesAction)
  113.  
  114.         coffeeNamesPublisher.foreach(println)
  115.  
  116.       }.flatMap { _ =>
  117.  
  118.         val u = true
  119.         // testing
  120.         val tes = coffees.filter(cofi => cofi.price > 4.5)
  121.             .filterOpt(zaFilter.name){case (row,ime) => row.name.like("%" + ime + "%")}
  122.             .filterIf(u)(a => a.price > 2.9)
  123.  
  124.  
  125.         println("STES statements:")
  126.         println(tes.result.statements)
  127.         println("PRINT NA STES:")
  128.         db.run(tes.result.map(println))
  129.  
  130.         /* Filtering / Where */
  131.  
  132.         // Construct a query where the price of Coffees is > 9.0
  133.         val filterQuery: Query[Coffees, (String, Int, Double, Int, Int), Seq] =
  134.           coffees.filter(_.price > 9.0)
  135.  
  136.         // Print the SQL for the filter query
  137.         println("Generated SQL for filter query:\n" + filterQuery.result.statements)
  138.  
  139.         // Execute the query and print the Seq of results
  140.         db.run(filterQuery.result.map(println))
  141.  
  142.       }.flatMap { _ =>
  143.  
  144.         /* Update */
  145.  
  146.         // Construct an update query with the sales column being the one to update
  147.         val updateQuery: Query[Rep[Int], Int, Seq] = coffees.map(_.sales)
  148.  
  149.         val updateAction: DBIO[Int] = updateQuery.update(1)
  150.  
  151.         // Print the SQL for the Coffees update query
  152.         println("Generated SQL for Coffees update:\n" + updateQuery.updateStatement)
  153.  
  154.         // Perform the update
  155.         db.run(updateAction.map { numUpdatedRows =>
  156.           println(s"Updated $numUpdatedRows rows")
  157.         })
  158.  
  159.       }.flatMap { _ =>
  160.  
  161.         /* Delete */
  162.  
  163.         // Construct a delete query that deletes coffees with a price less than 8.0
  164.         val deleteQuery: Query[Coffees,(String, Int, Double, Int, Int), Seq] =
  165.           coffees.filter(_.price < 8.0)
  166.  
  167.         val deleteAction = deleteQuery.delete
  168.  
  169.         // Print the SQL for the Coffees delete query
  170.         println("Generated SQL for Coffees delete:\n" + deleteAction.statements)
  171.  
  172.         // Perform the delete
  173.         db.run(deleteAction).map { numDeletedRows =>
  174.           println(s"Deleted $numDeletedRows rows")
  175.         }
  176.  
  177.       }.flatMap { _ =>
  178.  
  179.         /* Sorting / Order By */
  180.  
  181.         val sortByPriceQuery: Query[Coffees, (String, Int, Double, Int, Int), Seq] =
  182.           coffees.sortBy(_.price)
  183.  
  184.         println("Generated SQL for query sorted by price:\n" +
  185.           sortByPriceQuery.result.statements)
  186.  
  187.         // Execute the query
  188.         db.run(sortByPriceQuery.result).map(println)
  189.  
  190.       }.flatMap { _ =>
  191.  
  192.         /* Query Composition */
  193.  
  194.         val composedQuery: Query[Rep[String], String, Seq] =
  195.           coffees.sortBy(_.name).take(3).filter(_.price > 9.0).map(_.name)
  196.  
  197.         println("Generated SQL for composed query:\n" +
  198.           composedQuery.result.statements)
  199.  
  200.         // Execute the composed query
  201.         db.run(composedQuery.result).map(println)
  202.  
  203.       }.flatMap { _ =>
  204.  
  205.         /* Joins */
  206.  
  207.         // Join the tables using the relationship defined in the Coffees table
  208.         val joinQuery: Query[(Rep[String], Rep[String]), (String, String), Seq] = for {
  209.           c <- coffees if c.price > 9.0
  210.           s <- c.supplier
  211.         } yield (c.name, s.name)
  212.  
  213.         println("Generated SQL for the join query:\n" + joinQuery.result.statements)
  214.  
  215.         // Print the rows which contain the coffee name and the supplier name
  216.         db.run(joinQuery.result).map(println)
  217.  
  218.       }.flatMap { _ =>
  219.  
  220.         /* Computed Values */
  221.  
  222.         // Create a new computed column that calculates the max price
  223.         val maxPriceColumn: Rep[Option[Double]] = coffees.map(_.price).max
  224.  
  225.         println("Generated SQL for max price column:\n" + maxPriceColumn.result.statements)
  226.  
  227.         // Execute the computed value query
  228.         db.run(maxPriceColumn.result).map(println)
  229.  
  230.       }.flatMap { _ =>
  231.  
  232.         /* Manual SQL / String Interpolation */
  233.  
  234.         // A value to insert into the statement
  235.         val state = "CA"
  236.  
  237.         // Construct a SQL statement manually with an interpolated value
  238.         val plainQuery = sql"select SUP_NAME from SUPPLIERS where STATE = $state".as[String]
  239.  
  240.         println("Generated SQL for plain query:\n" + plainQuery.statements)
  241.  
  242.         // Execute the query
  243.         db.run(plainQuery).map(println)
  244.  
  245.       }*/
  246.  
  247.     val jj = Await.result(f, Duration.Inf)
  248.     println(jj)
  249.  
  250.   } finally db.close
  251. }
Advertisement
Add Comment
Please, Sign In to add comment