0

I am trying to construct a sql query with respect to optional query parameters from the endpoint.

e.g. I have a url http://localhost/api?one=1

Now form the above url I need to construct query somthing like ..

SELECT DISTINCT tb_one.id as id, tb_one.title as title from tb_one 
  JOIN
  tb_one ON tb_main.id = tb_one.id
  where other_id in (1) and tb_one.id in (2) 

and also e.g. i have a url http://localhost/api?one=1&two=1

SELECT DISTINCT tb_one.id as id, tb_one.title as title from tb_one 
      JOIN
      tb_one ON tb_main.id = tb_one.id 
      JOIN
      tb_two ON tb_main.id = tb_wo.id
      where other_id in (1) 

It could be n number of parameters with different combinations.

Can we construct a query like this in Go?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Hsn
  • 1,168
  • 2
  • 16
  • 39
  • 2
    *"Can we construct a query like this in golang?"* -- Yes, of course, using string concatenation you can construct any SQL query you like. Depending on how generic your requirements for the input and output of the sql generator are, you might be able to find 3rd party solution on the internet. But if your requirements are just a bit too specific, then you'll probably have to roll your own solution using programming. – mkopriva Mar 22 '21 at 13:51
  • thank you for the answer. I know and i am already doing that with string concatenagtion but its quite hard to first check the query parameter if it is present or not and then concat the string according to the amount of params. My problem is if i have 100 query parameter and then i have to write if else statement for each of the params. is it a good approach to still do it with string concatenation? – Hsn Mar 22 '21 at 14:40
  • Writing 100 if-else statements for a 100 query parameters does not sound like a good approach, it sounds more like a candidate for some form of abstraction. – mkopriva Mar 22 '21 at 15:29
  • Just to be clear, I am aware that my comments are vague and not very helpful but so is the problem description in the question. The two examples, both of which produce bad sql (at least considered bad in PostgreSQL, maybe it's ok in the sqlite dialect, or necessary for your use-case), seem incoherent to me, looking at them I am unable to infer some generic rules that could be put into an algorithm that would produce valid SQL. If you're looking for better answers you'll need to provide better questions and closer-to-reality code examples. – mkopriva Mar 22 '21 at 15:32

0 Answers0