I am trying to append or cbind a new column from R to a postgresql table. So, I have created a new column in the postgresql table where I want to put my dataframe column, i.e
ALTER TABLE schema.table
ADD COLUMN newcolumn "char";
library(RPostgres)
library(tidyverse)
library(rpostgis)
# SQL CONNECTION
fun_connect<-function(){dbConnect(RPostgres::Postgres(),dbname = 'mydb',
host = 'localhost', # i.e. 'ec2-54-83-201-96.compute-1.amazonaws.com'
port = 5432, # or any other port specified by your DBA
user = 'postgres',
password = 'secretpass'}
conn <- fun_connect()
mytable<-tbl(conn, "mydb")
# MY data frame
a<-data.frame(a= c("123","231543","1232","45389","4398543"))
# Trying to append or cbind my data frame column
#First try:
copy_to(conn,a,"newcolumn")
#Second try:
RPostgreSQL::dbWriteTable(conn, "table", a,append=T)
So i Have the next error:
Error: COPY returned error: ERROR: el valor nulo en la columna «FIRSTcolumn» de la relación «table» viola la restricción de no nulo
DETAIL: La fila que falla contiene (null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, 1).
CONTEXT: COPY table, línea 1: «10208011005»
Third try:
pgInsert(conn, name=c("schema","table"), a)
But I get:
1 out of 1 columns of the data frame match database table columns and will be formatted for database insert.
Error : Failed to fetch row: ERROR: el valor nulo en la columna «FIRSTcolumn» de la relación «table» viola la restricción de no nulo
DETAIL: La fila que falla contiene (null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, 1).
Insert failed. No changes made to database.
So I dont know how to append a new column from R to Postgresql in a simple way. I ask me if exist something similar to cbind(df, df2)
(lol) with df1 and df2 having the same nrow, but neither I don't have a proxy of how it's can be possible
Thanks for help me. Regards!