R/rows_upsert.R

Defines functions duckplyr_rows_upsert rows_upsert.duckplyr_df

# Generated by 02-duckplyr_df-methods.R
#' @export
rows_upsert.duckplyr_df <- function(x, y, by = NULL, ..., copy = FALSE, in_place = FALSE) {
  # Our implementation
  rel_try(NULL,
    "No relational implementation for rows_upsert()" = TRUE,
    {
      return(out)
    }
  )

  # dplyr forward
  rows_upsert <- dplyr$rows_upsert.data.frame
  out <- rows_upsert(x, y, by, ..., copy = copy, in_place = in_place)
  return(out)

  # dplyr implementation
  check_dots_empty()
  rows_df_in_place(in_place)

  y <- auto_copy(x, y, copy = copy)

  by <- rows_check_by(by, y)

  rows_check_x_contains_y(x, y)
  rows_check_contains_by(x, by, "x")
  rows_check_contains_by(y, by, "y")

  x_key <- dplyr_col_select(x, by)
  y_key <- dplyr_col_select(y, by)

  rows_check_unique(y_key, "y")

  args <- vec_cast_common(x = x_key, y = y_key)
  x_key <- args$x
  y_key <- args$y

  values_names <- setdiff(names(y), names(y_key))

  x_values <- dplyr_col_select(x, values_names)
  y_values <- dplyr_col_select(y, values_names)
  y_values <- rows_cast_y(y_values, x_values)

  loc <- vec_match(x_key, y_key)
  match <- !is.na(loc)

  y_loc <- loc[match]
  x_loc <- which(match)

  # Update
  y_values <- dplyr_row_slice(y_values, y_loc)
  x_values <- vec_assign(x_values, x_loc, y_values)
  x_values <- dplyr_new_list(x_values)

  x <- dplyr_col_modify(x, x_values)

  # Insert
  y_size <- vec_size(y_key)
  y_extra <- dplyr$vec_as_location_invert(y_loc, y_size)

  y <- dplyr_row_slice(y, y_extra)
  y <- rows_cast_y(y, x)

  x <- rows_bind(x, y)

  x
}

duckplyr_rows_upsert <- function(x, y, ...) {
  try_fetch(
    {
      x <- as_duckplyr_df(x)
      y <- as_duckplyr_df(y)
    },
    error = function(e) {
      testthat::skip(conditionMessage(e))
    }
  )
  out <- rows_upsert(x, y, ...)
  class(out) <- setdiff(class(out), "duckplyr_df")
  out
}
duckdblabs/duckplyr documentation built on Nov. 6, 2024, 10 p.m.