1

How can I create a table with a composite primary key with this library. For example:

CREATE TABLE something (
  column1, 
  column2, 
  column3, 
  PRIMARY KEY (column1, column2)
);

The only example I see in the documentation is a primary key on single column:

try db.run(users.create { t in     
    t.column(id, primaryKey: true)
    t.column(email, unique: true)  
    t.column(name)                 
}) 

I tried the following but fails with an error (...table "" has more than one primary key) :

 try db.run(tblTsMosStaged.create { t in
                        t.column(colTsMosStagedEventId, primaryKey: true)
                        t.column(colTsMosStagedEventInstance, primaryKey: true)
                        t.column(colTsMosStagedTaxId, primaryKey: true)
                        t.column(colTsMosStagedRankId)
...

Or is this only possible via Executing Arbitrary SQL

Paul
  • 652
  • 5
  • 16

1 Answers1

3

The SQLite.swift documentation says:

Table Constraints

Additional constraints may be provided outside the scope of a single column using the following functions.

  • primaryKey adds a PRIMARY KEY constraint to the table. Unlike the column constraint, above, it supports all SQLite types, ascending and descending orders, and composite (multiple column) keys.

    t.primaryKey(email.asc, name)
    // PRIMARY KEY("email" ASC, "name")
    
 try db.run(tblTsMosStaged.create { t in
                        t.column(colTsMosStagedEventId)
                        t.column(colTsMosStagedEventInstance)
                        t.column(colTsMosStagedTaxId)
                        t.column(colTsMosStagedRankId)
//ADD this line
                        t.primaryKey(colTsMosStagedEventId, colTsMosStagedEventInstance, colTsMosStagedTaxId)
GSerjo
  • 4,725
  • 1
  • 36
  • 55
Gwendal Roué
  • 3,949
  • 15
  • 34