Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

PRIMARY KEY option for createtable! function #286

Open
G-R-Martins opened this issue Mar 2, 2022 · 0 comments
Open

PRIMARY KEY option for createtable! function #286

G-R-Martins opened this issue Mar 2, 2022 · 0 comments

Comments

@G-R-Martins
Copy link

G-R-Martins commented Mar 2, 2022

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 G-R-Martins changed the title PRIMARY KEY option at createtable!() PRIMARY KEY option for createtable! function Mar 3, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant