1

Trying to adding a search feature for an existing GO micro service. DB: PostgreSQL. Right now, I am evaluating sqlc as an option. The requirement is to get the result with a single query from multiple tables, so the query will need to join tables. Challenge is that the number of input parameters varies, and need to return the result with a single query.
I am going to use following 3 tables as an example.

user
——————————————————————————
userId | firstName | lastName | bookingId |
——————————————————————————

flight ——————————————————————————————————————————————————————————————- flightId | departureCity | arrivalCity | departureTime | arrivalTime | departureDate | flightCompany | maxCap | ——————————————————————————————————————————————————————————————-

booking
—————————————————————————
bookingId | userId | flightId | bookingTime |
—————————————————————————

Goal:
Frontend UI could send only one or a combination of fields from following fields: bookingId, flightId, firstName, lastName. Then return single or multiple records to display the booking status. The record should contain, userId, bookingId, flightId, departureCity, arrivalCity, departureTime, arrivalTime, departureDate.

For example,

  1. Given a single bookingId, should return a single record, cause the bookingId was generated uniquely for that user.
  2. Given a flightId, should return a list of records, which are all the customers whoever booked this flight.
  3. Given firstName, lastName, and flightId, should get a single result (Assume no two people have the same name booked the same flight)
  4. Given only firstName, should give a list of records of the people with same firstName
  5. Given all 4 fields bookingId, flightId, firstName, lastName, then should return a single record.

In order to deal with the uncertain number of input parameters. I am thinking of using Sqlc.narg() and coalesce and conditional expression to have subqueries for different scenarios. But there are couple of questions.

  1. Sqlc.narg() and coalesce can be used together for updating table, no sure it can be used it with SELECT.
    Example from sqlc doc

    -- name: UpdateAuthor :one
    UPDATE author
    SET
    name = coalesce(sqlc.narg('name'), name),
    bio = coalesce(sqlc.narg('bio'), bio)
    WHERE id = sqlc.arg('id')
    RETURNING *;

  2. Due to the variety of the inputs, I believe I need to use condition expression. But the result expressions from CASE WHEN THEN must be convertible to a single output type. So, this won’t satisfy the case which returns multiple records. I am wondering if there are other alternatives.

wltz
  • 621
  • 1
  • 11
  • 22
  • 1
    Ref the uncertain number of input parameters" part; would something like `where (sqlc.narg(name)::text is null or sqlc.narg(name)::text = name)` work (basically `(param is null or param = value)` repeated for each optional parameter). – Brits Aug 20 '23 at 04:41

0 Answers0