Learn R Programming

dm (version 0.0.6.9000)

dm_add_pk: Add/remove a primary key to/from a table in a dm object

Description

dm_add_pk() marks the specified columns as the primary key of the specified table. If check == TRUE, then it will first check if the given combination of columns is a unique key of the table. If force == TRUE, the function will replace an already set key.

dm_rm_pk() removes a primary key from a table and leaves the dm object otherwise unaltered. Foreign keys that point to the table from other tables, can be optionally removed as well.

Usage

dm_add_pk(dm, table, columns, check = FALSE, force = FALSE)

dm_rm_pk(dm, table, rm_referencing_fks = FALSE)

Arguments

dm

A dm object.

table

A table in the dm.

columns

Table columns, unquoted.

check

Boolean, if TRUE, a check is made if the combination of columns is a unique key of the table.

force

Boolean, if FALSE (default), an error will be thrown if there is already a primary key set for this table. If TRUE, a potential old pk is deleted before setting a new one.

rm_referencing_fks

Boolean: if FALSE (default), will throw an error if there are foreign keys addressing the primary key that is to be removed. If TRUE, the function will remove, in addition to the primary key of the table argument, also all foreign key constraints that are pointing to it.

Value

For dm_add_pk(): An updated dm with an additional primary key.

For dm_rm_pk(): An updated dm without the indicated primary key.

Compound keys

Currently, keys consisting of more than one column are not supported. This feature is planned for dm 0.2.0. The syntax of these functions will be extended but will remain compatible with current semantics.

See Also

Other primary key functions: dm_get_all_pks(), dm_get_pk(), dm_has_pk(), enum_pk_candidates()

Examples

Run this code
# NOT RUN {
library(dplyr)

nycflights_dm <- dm_from_src(src_df(pkg = "nycflights13"))

# the following works
dm_add_pk(nycflights_dm, planes, tailnum)
dm_add_pk(nycflights_dm, airports, faa, check = TRUE)
dm_add_pk(nycflights_dm, planes, manufacturer)

# the following does not work (throws an error)
try(dm_add_pk(nycflights_dm, planes, manufacturer, check = TRUE))
library(dplyr)
nycflights_dm <- dm_nycflights13()

nycflights_dm %>%
  dm_rm_pk(airports, rm_referencing_fks = TRUE) %>%
  dm_has_pk(planes)

nycflights_dm %>%
  dm_rm_pk(planes, rm_referencing_fks = TRUE) %>%
  dm_has_pk(planes)
# }

Run the code above in your browser using DataLab