postgresqltypesjuliaalterlibpq

Julia, get and set a column datatype in PostgreSQL


I've searched a lot everywhere, but could not find a clear solution, despite this is, I thihk, a basic simple question. Finally wanna make clear this. :p

The basic problem is how to get datatype or convert,maybe.

ex. Type[String] -> String

Ok, the behind is.... I am trying to move a data from A_table to B_table. For preparating B_table, have to add 'name' column that is the same type with A_table as you know. Then I do

dtype = LibPQ.columntypes(execute(conn,"name"))           <-1.get the data type
alterstr = """alter talbe .... add column name $dtype"""  <-2.create add sentence
execute(conn,alterstr)                                    <-3.then done

The 1 return 'dtype=Type[String]', as you know this does not fit on SQL. I have an idea that load the A_table to DataFrames(DF), then rely on DF column data type insted of 1 process. Indeed it can be, but I believe it can be simplifed without DF. The tips in LibPQ are OK as well.(^_-)

Teach me the basic on. Many thanks.


Solution

  • There are many ways to do the basic conversion Type{T} -> T. For example accessing the parameters field:

    julia> Type{String}.parameters[1]
    String
    

    or lifting the value into the type to dispatch to a method returning the type:

    type_param(t::DataType) = type_param(Val(t))
    type_param(::Val{Type{T}}) where T = T
    
    julia> type_param(Type{String})
    String
    

    this approach makes it easy to define special cases:

    type_param_name(t::DataType) = type_param_name(Val(t))
    type_param_name(::Val{Type{T}}) where T = string(T)
    type_param_name(::Val{Type{String}}) = "text"
    
    
    julia> type_param_name(Type{Int})
    "Int64"
    
    julia> type_param_name(Type{String})
    "text"