SQLite.jl icon indicating copy to clipboard operation
SQLite.jl copied to clipboard

PRIMARY KEY option for createtable! function

Open G-R-Martins opened this issue 3 years ago • 0 comments

I think a method able to create a table with a primary key could be very helpful, but I didn't find any -- I am sorry if such a method already exists!

In my source code I just created a new createtable! function (as shown below) but probably there is a better way (I am quite new to Julia).

function createtable!(db::SQLite.DB, nm::AbstractString, ::Tables.Schema{names, types}; temp::Bool=false, ifnotexists::Bool=true, primarykey::Int=0) where {names, types}
    temp = temp ? "TEMP" : ""
    ifnotexists = ifnotexists ? "IF NOT EXISTS" : ""
    typs = [types === nothing ? "BLOB" : sqlitetype(fieldtype(types, i)) for i = 1:length(names)]
    
    if primarykey > 0
        (typs[primarykey] *= " PRIMARY KEY")
    end

    columns = [string(esc_id(String(names[i])), ' ', typs[i]) for i = 1:length(names)]
    return execute(db, "CREATE $temp TABLE $ifnotexists $nm ($(join(columns, ',')))")
end

The drawback is that I cannot define only Integer in the function call, I have to set Union{missing, Integer}. So an alternative approach to make syntax easier might be to create methods for the sqlitetype function that includes an optional parameter isprimary:

sqlitetype(::Type{T}, isprimary::Bool=false) where {T<:Integer} = isprimary ? "INTEGER PRIMARY KEY" : "INTEGER NOT NULL" ;

Furthermore, I noticed the feature only works properly if we define "INTEGER" and not "INT", as it is in the sqlitetype function. So it should be "INTEGER PRIMARY KEY", otherwise when INSERT data without the primary key it might be set to NULL.

G-R-Martins avatar Mar 02 '22 23:03 G-R-Martins