% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/unique-keys.R
\name{dm_add_uk}
\alias{dm_add_uk}
\title{Add a unique key}
\usage{
dm_add_uk(dm, table, columns, ..., check = FALSE)
}
\arguments{
\item{dm}{A \code{dm} object.}

\item{table}{A table in the \code{dm}.}

\item{columns}{Table columns, unquoted.
To define a compound key, use \code{c(col1, col2)}.}

\item{...}{These dots are for future extensions and must be empty.}

\item{check}{Boolean, if \code{TRUE}, a check is made if the combination of columns is a unique key of the table.}
}
\value{
An updated \code{dm} with an additional unqiue key.
}
\description{
\code{dm_add_uk()} marks the specified columns as a unique key of the specified table.
If \code{check == TRUE}, then it will first check if
the given combination of columns is a unique key of the table.
}
\details{
The difference between a primary key (PK) and a unique key (UK) consists in the following:
\itemize{
\item When a local \code{dm} is copied to a database (DB) with \code{copy_dm_to()}, a PK will be set on the DB by default, whereas a UK is being ignored.
\item A PK can be set as an \code{autoincrement} key (also implemented on certain DBMS when the \code{dm} is transferred to the DB)
\item There can be only one PK for each table, whereas there can be unlimited UKs
\item A UK will be used, if the same table has an autoincrement PK in addition, to ensure that during delta load processes
on the DB (cf. \code{\link[=dm_rows_append]{dm_rows_append()}}) the foreign keys are updated accordingly.
If no UK is available, the insertion is done row-wise, which also ensures a correct matching, but can be much slower.
\item A UK can generally enhance the data model by adding additional information
\item There can also be implicit UKs, when the columns addressed by a foreign key are neither a PK nor a UK.
These implicit UKs are also listed by \code{\link[=dm_get_all_uks]{dm_get_all_uks()}}
}
}
\examples{
\dontshow{if (rlang::is_installed(c("nycflights13", "DiagrammeR"))) withAutoprint(\{ # examplesIf}

nycflights_dm <- dm(
  planes = nycflights13::planes,
  airports = nycflights13::airports,
  weather = nycflights13::weather
)

# Create unique keys:
nycflights_dm \%>\%
  dm_add_uk(planes, tailnum) \%>\%
  dm_add_uk(airports, faa, check = TRUE) \%>\%
  dm_add_uk(weather, c(origin, time_hour)) \%>\%
  dm_get_all_uks()

# Keys can be checked during creation:
try(
  nycflights_dm \%>\%
    dm_add_uk(planes, manufacturer, check = TRUE)
)
\dontshow{\}) # examplesIf}
}
\seealso{
Other primary key functions:
\code{\link[=dm_add_pk]{dm_add_pk()}},
\code{\link[=dm_get_all_pks]{dm_get_all_pks()}},
\code{\link[=dm_get_all_uks]{dm_get_all_uks()}},
\code{\link[=dm_has_pk]{dm_has_pk()}},
\code{\link[=dm_rm_pk]{dm_rm_pk()}},
\code{\link[=dm_rm_uk]{dm_rm_uk()}},
\code{\link[=enum_pk_candidates]{enum_pk_candidates()}}
}
\concept{primary key functions}
