Where communities thrive


  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
People
Repo info
Activity
    Saif Addin
    @saif-ellafi
    so I was never returning Futures anywhere actually, and they were being just side-effects of the functions..
    but totally your proposal is much cleaner, I'll figure a way of returning both the temporary result and the Future, perhaps a Tuple
    something like
      def addEvents(entryEvents: Seq[EntryEvent]) = {
        val now = LocalDateTime.now()
        val newEvents = entryEvents.map(e => Event(0, now, e.employeeId, e.teamId, e.projectId, e.companyId, e.notes))
        val task = tables.db.run(tables.events ++= newEvents)
        (newEvents, task)
      }
    That was really useful, appreciated
    KLM
    @lakshmankollipara

    Question:
    Insert into a Table from Raw SQL Select

    val rawSql: DBIO[Vector[(String, String)]] = sql"SELECT id, name FROM SomeTable".as[(String, String)]
    val myTable :TableQuery[MyClass] // with columns id, name and some other columns

    Is there a way to use forceInsert functions to insert data from select into the tables?
    If not, Is there a way to generate a sql string by using forceInsertStatements?
    Something like:

    db.run {
              myTable.map{ t => (t.id, t.name)}.forceInsert????(rawSql)
    }

    Thanks for the help.

    Philipp Dörfler
    @phdoerfler
    Hi! In SQL I can do UPDATE … SET something = (SELECT … FROM …). I don't see how I can do the same in Slick. Is that even possible and if so, how so? Thanks!
    Philipp Dörfler
    @phdoerfler
    I should add that unfortunately I'm on Slick 2.1.0
    I understand that in Slick 3 there is forceInsertQuery which seems to this but for inserts, and there are DBIO Actions which apparently let me update values based on a computation. But is there a forceUpdateQuery or do I indeed use DBIO Actions for this purpose?
    James Phillips
    @jdrphillips
    Hi. I've a question about generating Shapes
    I have a very ordinary set up, with a case class User and a Users table
    However, I need to generate a Shape[FlatShapeLevel, Users, User, Users] outside of class Users
    I cannot summon it implicitly from the top - as the topmost level which accepts implicit parameters does not know about the existence of Users
    (probably not a "very ordinary" setup after all)

    So, how do I write this line:

      implicit def userShape: Shape[FlatShapeLevel, Users, User, Users] = ...

    ?

    Any help would be greatly appreciated!
    Note again at this point, we are outside of the Users table, and so cannot access the columns within it
    Alexandre Roba
    @AlexandreRoba
    Hi all, I having some difficulties using groupBy with Slick.
    This is my slick code:
      override def getPaymentErrorsByBookingIds(bookingIds: Seq[UUID]): DBIO[Seq[(UUID, Seq[PaymentError])]] =
        paymentErrors
          .filter(b => b.bookingId inSet bookingIds)
          .groupBy(_.bookingId)
          .map {
            case (bookingId, errors) => bookingId -> errors
          }
          .result
    The Payment Error table looks like:
    trait PaymentErrorTable {
      class PaymentErrors(tag: Tag) extends Table[PaymentError](tag, "payment_error") {
        def newIdWhenInserting: UUID = UUID.randomUUID()
    
        def currentWhenInserting = new Timestamp((new Date).getTime)
    
        def id              = column[UUID]("id", O.Default(newIdWhenInserting), O.PrimaryKey)
        def bookingId       = column[UUID]("booking_id")
        def paymentMethodId = column[String]("payment_method_id")
        def error           = column[String]("error")
        def amount          = column[BigDecimal]("amount")
        def currency        = column[Currency]("currency")
        def createdAt       = column[Timestamp]("created_at", O.Default(currentWhenInserting))
        def * =
          (
            id,
            bookingId,
            paymentMethodId,
            error,
            amount,
            currency,
            createdAt
          ) <> ((PaymentError.apply _).tupled, PaymentError.unapply)
      }
      protected val paymentErrors = TableQuery[PaymentErrors]
    }
    Unfortunattely when compiling I'm getting the following error:
    No matching Shape found.
    Slick does not know how to map the given types.
    Possible causes: T in Table[T] does not match your * projection,
     you use an unsupported type in a Query (e.g. scala List),
     or you forgot to import a driver api into scope.
      Required level: slick.lifted.FlatShapeLevel
         Source type: (slick.lifted.Rep[java.util.UUID], slick.lifted.Query[JdbcPaymentErrorStorage.this.PaymentErrors,booking.PaymentError,[+A]Seq[A]])
       Unpacked type: T
         Packed type: G
    
          .map {
    Alexandre Roba
    @AlexandreRoba
    I've got a feeling that groupbycan only be used with aggregate functions...
    Richard Dallaway
    @d6y
    Yeah, I'd do the aggregation into (what is effective, kind of) a map client-side. You could totally count the errors but I don't think you can aggregate like that. (I'm not sure what the SQL would be to return a row containing an id and a list of errors... although there's probably a way to do it in Postgres: it seems to have all the toys 😍 )
    vyshnavi-adusumelli
    @vyshnavi-adusumelli
    Hi, In slick we generally mention the database credentials in application.conf. But is there any way we can configure these credentials through code? Basically I wanted to retrieve the DB credentials from aws secret manager and then configure them using slick. How should I proceed?
    kk3009
    @kk3009
    @vyshnavi-adusumelli have you tried creating a scala object to configure hilaki data source, it basically takes all the params and you could import it from anywhere you want? Then use JdbcBackend.Database.forDataSource to create a db object.
    1 reply
    *hikari
    Konstantin Simeonov
    @KonstantinSimeonov

    Hi everyone, I'm using plainsql slick queries and I'm running into the following issue:

    Caused by: org.postgresql.util.PSQLException: ERROR: column "expiry_date" is of type timestamp without time zone but expression is of type character varying

    The column in question is of type timestamp with timezone.

    Here's how I build my query:

        val query = sqlu"""INSERT INTO "offers"
        VALUES (
                  ${c.userId.toInt},
                  ${c.categoryId.toInt},
                  ${new Timestamp(Instant.now.toEpochMilli)},
                  ${new Timestamp(c.expiryDate)},
                  ${c.description},
                  ${c.address},
                  ${c.latitude},
                  ${c.longitude},
                  ${new Timestamp(c.startAt)},
                  ${new Timestamp(c.endAt)},
                  ${c.compensation},
                  ${c.imageUrl},
                  ${c.requirements},
                  ${c.title}
        )"""
    2 replies
    Renato Cavalcanti
    @octonato
    Hi @/all
    Slick v3.3.3 is out: https://github.com/slick/slick/releases/tag/v3.3.3
    Enjoy!
    1 reply
    Georgios Larkou
    @glarkou
    ```
    Case.If(aquery.length>0) Then bquery else cquery
    It seems that the following does not work, what is the suggested way to perform different queries based on the length of the previous one?
    2 replies
    Antoine Doeraene
    @sherpal
    @renatocaval thanks! Are there any open points where it could be a good point to jump in and provide some help?
    18 replies
    Arsene
    @Tochemey
    Hello can someone show me the full slick reference.conf for postgres db with connection pool. It seems the documentation is a bit all over the place for me.
    1 reply
    Blaž Marinović
    @bmarinovic

    hi all! :) I'm having a problem with values interpolation in raw SQL. This works on PostgreSQL CLI:

    select file_name from (values ('file1'), ('file2'), ('file3')) AS t (file_name) except select file_name from processed_s3_files;

    I was expecting this to work:

    val fileNamesAsValues = fileNames.map(fn => s"('$fn')").mkString(", ")
    sql"""select "file_name" from (values $fileNamesAsValues) AS t ("file_name") except select "file_name" from "processed_s3_files"""".as[String]

    but I get org.postgresql.util.PSQLException: ERROR: syntax error at or near "$1"

    Antoine Doeraene
    @sherpal
    You need # in front of the $. It's documented here http://scala-slick.org/doc/3.3.2/sql.html
    David Leonhart
    @leozilla

    Hi, I am having problems with using Instant with the newest h2 version 1.4.200.

    I am getting the following error:

    org.h2.jdbc.JdbcSQLDataException: Cannot parse "TIMESTAMP" constant "aced0005740014323039392d30312d30315430383a30303a30305a"; SQL statement:

    With previous versions I used a custom column mapper to work around errors with H2.

      protected implicit val H2InstantMapper: BaseColumnType[Instant] = MappedColumnType.base[Instant, Timestamp](
        w => Timestamp.from(w),
        r => r.toInstant
      )

    But this does not work anymore with the newest version.

    I also needed to use the PostgresProfile instead of the H2Profile because the BLOB data type was not working anymore.

    Can anyone help me with figuring out how to use Instant both with H2 (which I use in tests) and Postgres (which I use in prod)?
    I tried around for hours now and I am stuck..

    Matt Fulgo
    @mfulgo

    Hi folks,
    This has been covered a good bit in StackOverflow questions & in other places, but I have yet to find a solution that I'm happy with... I want to create an UPDATE statement with a variable number of columns. Something like

    coffees.filter(_.id === id)
      .map(t => change.cols(t))  // cols(t) returns Seq[Rep[_]]
      .update(change.values)  // values returns a Seq[_]

    I feel like there could be a way to do this with a custom Shape (like TupleShape but for Seq), but I was hoping for some more experienced folks to tell me if this is a futile endeavor or if it's a viable approach.

    There's also this gist but I'd rather not have to create a custom driver or rely on regexes to manipulate the query.

    Richard Dallaway
    @d6y
    I think it'll be tricky to get far with Seq, as I'd imagine a lot of type information (for each column) will get lost away to Any. I'd be tempted to use something like slick.collection.heterogeneous.HList, and there would be some fun/challenging type-level methods to get the types to exactly line up for cols and values.
    There might be easier ways. Depending on what you're basing the change on.
    If your data is a case class, maybe you can merge the values and update the whole role. As inspiration: https://github.com/davegurnell/bulletin (i.e., drop the map and just do the update; probably not suitable if you're shiping large amounds of data in a row)
    Matt Fulgo
    @mfulgo

    Thanks, Richard. In this case, I'm okay with missing out on some type safety. For the moment, I've ended up with something along these lines:

        SQLActionBuilder(
          Seq(s"UPDATE $tableName SET ",
            cols.map(_.getDumpInfo.mainInfo + " = ?").mkString(", "),
            " WHERE ID = ?",
            " LIMIT 1",
          ),
          (_: Unit, pp: PositionedParameters) => {
            (values :+ id).foreach {
              case v: Boolean => pp.setBoolean(v)
              case v: Byte => pp.setByte(v)
              case v: Date => pp.setDate(v)
              case v: Double => pp.setDouble(v)
              case v: Float => pp.setFloat(v)
              case v: Int => pp.setInt(v)
              case v: Long => pp.setLong(v)
              case v: Short => pp.setShort(v)
              case v: String => pp.setString(v)
              case v: Time => pp.setTime(v)
              case v: Timestamp => pp.setTimestamp(v)
              case v => throw new SQLException("update doesn't know how to handle parameter (" + v + ")")
            }
          }).asUpdate

    It's not quite complete because it doesn't handle NULLs, but it works for my current needs.

    Martijn Blankestijn
    @martijnblankestijn
    Hi, been searching everywhere, but was not able to find how to do the following:

    Given the following for PostgreSQL

    CREATE TABLE IF NOT EXISTS X(id INT PRIMARY KEY, name VARCHAR not null);
    
    select *from X x where (x.id, x.name) in ( (1,'foo'), (2,'bar'))
    ;

    how do I do this with Slick 3.3.3? The compiler never seems to agree with me

    Richard Dallaway
    @d6y
    Ah yes... inSet doesn't seem to support tuples. We might be able to teach Slick how to do that, but the workaround would be to transform into a (id ===1 && name == "foo") or (id === 2 && name === "bar"). Sounds horrible, but the code isn't too much. Old example: https://github.com/d6y/list-of-tuples/blob/eaa2903332d7797ac38d8807fa598fd2a5aad344/src/main/scala/or-example.scala#L52-L55
    Martijn Blankestijn
    @martijnblankestijn
    Will give it a try, thanks @d6y !
    mehdi
    @hmehdi
    Hi, I want to connect from slick to mssql when select to the table contain column type NVarchar don't return the result for me. because slick don't add character N ( Unicode NVARCHAR Strings) . how can cusotme fucntion add N character.
    ex) select * from customer where title like N'%tt%'
    how can I enable the unicode prefix in slick?
    plz help me
    Felipe Bonezi
    @felipebonezi
    Hey guys, is there anyone working on MongoDB support for Slick?
    Richard Dallaway
    @d6y
    @felipebonezi Not that I know of. There was some investigation some years back (there are still open tickets mentioning MongoDB).
    Felipe Bonezi
    @felipebonezi
    @d6y Do you know any way to study more about Slick implementations and your archicture?
    I'm intended to try implement MongoProfile or to improve my skills hehehe.