I was interacting with a SQL database using Clojure and needed to create a table so I turned to create-table from clojure.contrib.sql. Looking at the docs for create-table it seemed pretty straight forward. To create a table with columns date, id, symbol, price, and quantity you would write the following.
1 2 3 4 5 6 | |
The above works. I also wanted to specify that columns date and id to form a composite primary key. I wasn’t sure how to specify a composite primary key with create-table and ended up diving into its code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | |
Looking at create-table we can see it creates a SQL statement which is then executed by do-commands. In order to have a composite key we need do-commands to execute a SQL statement that looks similar to below.
1 2 3 4 5 6 7 8 | |
Let’s break down create-table to figure out what we need to pass it to make do-commands run the above statement. The code for create-table is repeated below with comments pointing out what step lines up the code.
1 2 3 4 5 6 7 8 9 10 | |
- First
create-tabletakes the sequences inspecsand puts a space between each element in each sequence. - The result of step 1 then has a vector containing a comma and a space interposed between each element of it.
concatcombined withapplyis used to combine each element of the result of step 2 into a single sequence.as-str(from c.c.string) is mapped over the result of step 3 to make sure every element is a string.stris used to make one string out of the sequence of strings from step 4.formatis used to substitute innameand the result of step 5 to create the SQL statement.do-commandsexecutes the statement created in step 6.
Knowing how create-table works now allows us to specify the arguments that will create the orders table with the composite primary key of date and id.
1 2 3 4 5 6 7 | |