| Title: | An Abstracted System for Easily Working with Databases with Large Datasets |
|---|---|
| Description: | Provides object-oriented database management tools for working with large datasets across multiple database systems. Features include robust connection management for 'PostgreSQL' databases, advanced table operations with bulk data loading and upsert functionality, comprehensive data validation through customizable field type and content validators, efficient index management, and cross-database compatibility. Designed for high-performance data operations in surveillance systems and large-scale data processing workflows. |
| Authors: | Richard Aubrey White [aut, cre] (ORCID: <https://orcid.org/0000-0002-6747-1726>), August Sørli Mathisen [aut], Folkehelseinstituttet [cph] |
| Maintainer: | Richard Aubrey White <[email protected]> |
| License: | MIT + file LICENSE |
| Version: | 2026.12.5 |
| Built: | 2026-12-05 01:10:11 UTC |
| Source: | https://github.com/niphr/csdb |
collect_and_sort_by_pk() replaces dplyr::collect() for a query that
starts at DBTable_v9$tbl(). It returns a data.table, ordered by the
primary key of that table and then by every other column.
collect_and_sort_by_pk(x)collect_and_sort_by_pk(x)
x |
A lazy table that starts at DBTable_v9 |
PostgreSQL returns rows in no fixed order. The same query can return the
same rows in a different order on each call. Code that reads d[1],
d[.N] or tail(d, 1) after dplyr::collect() therefore gets an arbitrary
row. collect_and_sort_by_pk() makes that row deterministic.
DBTable_v9$tbl() attaches the primary key of the table to the lazy table
as the attribute csdb_pk. These dbplyr verbs keep the attribute on their
result: filter(), select(), mutate(), group_by(), summarise(),
arrange(), distinct(), head(), and left_join() and inner_join() on
the x side.
The function sorts with setorder_by_pk(). The primary key columns that
the result has come first, in primary key order. Every other column follows,
in column order. A primary key column that a select() or a summarise()
removed is not a sort column.
The attribute holds column names. After a rename() or a mutate() of a
primary key column, the order is still fixed, but it is no longer the
primary key order.
The sort runs after the collect. It cannot choose which rows a head() or
another limit inside the query returns. Put a dplyr::arrange() before the
limit when the rows matter.
The function stops with an error when x carries no primary key. It does
not fall back to an unsorted collect. These are the causes:
the query did not start at DBTable_v9$tbl().
the table has no primary key, because its keys is NULL.
a step dropped the attribute, for example dplyr::compute(), or a join
where the csdb table is on the y side.
For a result without a primary key, for example from DBI::dbGetQuery(),
use setorder_by_pk() with table = NULL.
A data.table with the rows of x, sorted as described in Details.
Other row order:
set_pk(),
setorder_by_pk()
# SQLite needs no server, so this block runs anywhere. my_table <- DBTable_v9$new( dbconfig = list(driver = "SQLite", db = tempfile(fileext = ".sqlite")), table_name = "my_data_table", field_types = c("id" = "INTEGER", "week" = "INTEGER", "n" = "DOUBLE"), keys = c("id", "week") ) my_table$insert_data(data.table::data.table( id = c(2L, 1L, 2L, 1L), week = c(2L, 2L, 1L, 1L), n = c(4, 3, 2, 1) )) d <- my_table$tbl() |> dplyr::filter(id == 1L) |> collect_and_sort_by_pk() # The last row is the last week of id 1, on every database. d[.N] my_table$disconnect()# SQLite needs no server, so this block runs anywhere. my_table <- DBTable_v9$new( dbconfig = list(driver = "SQLite", db = tempfile(fileext = ".sqlite")), table_name = "my_data_table", field_types = c("id" = "INTEGER", "week" = "INTEGER", "n" = "DOUBLE"), keys = c("id", "week") ) my_table$insert_data(data.table::data.table( id = c(2L, 1L, 2L, 1L), week = c(2L, 2L, 1L, 1L), n = c(4, 3, 2, 1) )) d <- my_table$tbl() |> dplyr::filter(id == 1L) |> collect_and_sort_by_pk() # The last row is the last week of id 1, on every database. d[.N] my_table$disconnect()
Returns FALSE when a catalog request on connection shows that the
connection lost its server. Use it before cleanup SQL on a connection that
MAY have lost its server.
csdb_connection_is_alive(connection)csdb_connection_is_alive(connection)
connection |
A DBI connection, or NULL. |
DBI::dbIsValid() cannot answer this question. It reports TRUE on an
odbc connection whose server ended the session. On such a connection, the
first statement gives an R error. The second statement crashes R with a
segfault in odbc 1.7.0 with psqlODBC 13.02, and tryCatch() cannot
catch a segfault.
The function asks the server whether the table csdb_connection_probe
exists. odbc sends that request as an ODBC catalog call, not as a
statement. On a lost connection it gives an R error, also after a failed
statement. This was measured on 2026-10-22 against PostgreSQL 16.15.
Only a condition whose message shows a lost connection gives FALSE. Any
other error or warning of the request gives TRUE, so a live connection
still gets its cleanup SQL. See csdb_connection_lost_pattern in the
source for the messages.
PostgreSQL releases the advisory locks, the role and the temporary tables of a session when the session ends. Cleanup SQL for them then has nothing to do.
TRUE or FALSE. FALSE for NULL, for a closed connection, and when the catalog request gives a condition that shows a lost connection.
con <- DBI::dbConnect(RSQLite::SQLite(), ":memory:") csdb_connection_is_alive(con) DBI::dbDisconnect(con) csdb_connection_is_alive(con)con <- DBI::dbConnect(RSQLite::SQLite(), ":memory:") csdb_connection_is_alive(con) DBI::dbDisconnect(con) csdb_connection_is_alive(con)
Returns the currently registered authentication hook function.
csdb_get_auth_hook()csdb_get_auth_hook()
The current authentication hook function, or NULL when no hook is set.
DBConnection_v9, whose connect() method calls
this function to look up the hook.
The introduction vignette,
vignette("csdb", package = "csdb"), does not mention this function.
Other auth hook functions:
csdb_set_auth_hook()
# Returns NULL when no hook has been set csdb_get_auth_hook() # Register a hook and then read it back. Registering does not call it. previous <- csdb_set_auth_hook(function() { system2("/bin/kinit", stdout = NULL) }) hook <- csdb_get_auth_hook() is.function(hook) csdb_set_auth_hook(previous)# Returns NULL when no hook has been set csdb_get_auth_hook() # Register a hook and then read it back. Registering does not call it. previous <- csdb_set_auth_hook(function() { system2("/bin/kinit", stdout = NULL) }) hook <- csdb_get_auth_hook() is.function(hook) csdb_set_auth_hook(previous)
Returns the string that csdb_set_context() set.
csdb_get_context()csdb_get_context()
One string, "" when no context is set.
Other caller context functions:
csdb_set_context()
csdb_get_context()csdb_get_context()
Returns the function that csdb_set_password_hook registered.
csdb_get_password_hook()csdb_get_password_hook()
The current password hook function, or NULL when no hook is set.
Other password hook functions:
csdb_set_password_hook()
# Returns NULL when no hook is set. csdb_get_password_hook()# Returns NULL when no hook is set. csdb_get_password_hook()
Registers a function that csdb calls when a database connection fails. Use it to refresh a Kerberos ticket, or other authentication credentials, before the next connection attempt.
csdb_set_auth_hook(hook)csdb_set_auth_hook(hook)
hook |
A function with no arguments that performs authentication, or NULL to clear the hook. |
Invisibly returns the previous hook (if any).
DBConnection_v9, whose connect() method calls
the registered hook once, after its first failed attempt.
The introduction vignette,
vignette("csdb", package = "csdb"), does not mention this function.
Other auth hook functions:
csdb_get_auth_hook()
# The hook is held in the csdb.auth_hook option. Setting one returns # the previous hook, so it can be put back afterwards. previous <- csdb_set_auth_hook(function() invisible(NULL)) is.function(csdb_get_auth_hook()) csdb_set_auth_hook(previous) csdb_get_auth_hook() # A real hook refreshes a credential, for example a Kerberos ticket. # Registering the hook does not call it, so this block runs on a # machine that has no such script. previous <- csdb_set_auth_hook(function() { system2("/bin/authenticate.sh", stdout = NULL) }) is.function(csdb_get_auth_hook()) # Put back whatever was registered before. csdb_set_auth_hook(previous)# The hook is held in the csdb.auth_hook option. Setting one returns # the previous hook, so it can be put back afterwards. previous <- csdb_set_auth_hook(function() invisible(NULL)) is.function(csdb_get_auth_hook()) csdb_set_auth_hook(previous) csdb_get_auth_hook() # A real hook refreshes a credential, for example a Kerberos ticket. # Registering the hook does not call it, so this block runs on a # machine that has no such script. previous <- csdb_set_auth_hook(function() { system2("/bin/authenticate.sh", stdout = NULL) }) is.function(csdb_get_auth_hook()) # Put back whatever was registered before. csdb_set_auth_hook(previous)
Sets a short string that names the caller, for example
"<task>|<plan>". PostgreSQL shows it as the application_name
of each csdb connection in pg_stat_activity.
csdb_set_context(x)csdb_set_context(x)
x |
One string. |
With a non-empty context, csdb runs SET application_name with the
context right after each PostgreSQL connection that
DBConnection_v9 opens. After a failed SET, csdb runs
SELECT 1. A connection that answers stays open and reports nothing.
A connection that does not answer counts as a failed connect attempt. A
PostgreSQL load uses that connection, so it shows the same name.
The name keeps only the letters A-Z and a-z, the digits 0-9 and the
characters _ | . : -. csdb drops every other character, and then
keeps the first 63 characters, the limit of PostgreSQL. A context that
keeps no character sends no SET.
The context is an option, so a forked worker inherits it. A new R process,
for example one that callr starts, does not.
Do not put a secret in the context. pg_stat_activity shows it.
Invisibly returns the previous context.
Other caller context functions:
csdb_get_context()
previous <- csdb_set_context("my_task|plan7") csdb_get_context() csdb_set_context(previous)previous <- csdb_set_context("my_task|plan7") csdb_get_context() csdb_set_context(previous)
Registers a function that returns the password for each new PostgreSQL connection. Use it for a password that expires, such as an Entra access token.
csdb_set_password_hook(hook)csdb_set_password_hook(hook)
hook |
A function with no arguments that returns the password, or NULL to clear the hook. |
csdb calls the hook with no arguments, once for each attempt of
DBConnection_v9$connect() with the driver
"PostgreSQL Unicode". It uses the current return value as the
password. A PostgreSQL load uses the connection, and calls the hook only
when it opens a new one.
The hook MUST return a single non-empty string. Any other value stops the connection with an error that names the hook. The error does not show the value.
The hook applies to PostgreSQL only. A SQL Server, SQLite or other
connection, and a bcp load, use the password in their settings.
csdb therefore never sends the hook value to another kind of server.
The message of a failed connection shows *** in place of the hook
value.
Invisibly returns the previous hook, or NULL when no hook was set.
csdb_set_auth_hook registers a function that
DBConnection_v9$connect() calls after its first failed attempt.
Other password hook functions:
csdb_get_password_hook()
# The hook is held in the csdb.password_hook option. Registering the hook # does not call it. previous <- csdb_set_password_hook(function() "example-token") is.function(csdb_get_password_hook()) # Put back whatever was registered before. csdb_set_password_hook(previous) csdb_get_password_hook()# The hook is held in the csdb.password_hook option. Registering the hook # does not call it. previous <- csdb_set_password_hook(function() "example-token") is.function(csdb_get_password_hook()) # Put back whatever was registered before. csdb_set_password_hook(previous) csdb_get_password_hook()
A database connection manager that handles connections to various database systems including Microsoft SQL Server and PostgreSQL. This class provides connection management, authentication, and automatic reconnection.
The DBConnection_v9 class holds the database connection logic and provides a consistent interface to different database systems. It supports both trusted connections and user/password authentication. It handles connection failures, and it reconnects automatically.
Key features:
Support for multiple database systems (SQL Server, PostgreSQL).
Automatic connection management with retry logic.
Secure credential handling.
Connection status monitoring.
Graceful error handling and recovery.
A connection is never shared with another process.
A connection belongs to the process that opened it. After a fork, the child
holds a copy of this object and a copy of the parent's connection. Both
processes then use one socket. PostgreSQL can return wrong results and
report no error. Measured against the NorSySS server on 2026-08-14. A child
asked for select 4 and read 3. The parent asked for
select 999 and read 2. DBI::dbIsValid() reports TRUE on such a
handle, so nothing else detects it.
This class records the process that opens each connection. It drops any
connection whose recorded process is not the current one.
is_connected() then returns FALSE, connection returns NULL,
and autoconnection opens a new connection for the current process.
disconnect() closes nothing, because the handle belongs to the other
process.
The object never closes an inherited handle, and it keeps a reference to it.
Both parts are needed. A close, by DBI::dbDisconnect() or by the
garbage collector, would close the other process's socket.
DBTable_v9$insert_data(), $upsert_data() and
insert_data_many send rows to PostgreSQL as JSON text over
this connection. csdb starts no client, so a load makes no new login. One
statement sends at most 500,000 rows, and every statement of one load runs
in one transaction.
csdb finds the failure class in the English error text of the server. Each
new connection warns once when the lc_messages of the server is not
C, POSIX or English. A failed load is csdb_load_ambiguous unless its
ROLLBACK succeeded and the connection then answered SELECT 1. Only
then can a known English text give csdb_load_duplicate_key or
csdb_load_transient. Any other text gives csdb_load_other.
The COMMIT and a broken connection also give csdb_load_ambiguous.
Three more rules apply:
A statement that runs past load_timeout stops on the server,
which stores no row. The error has class csdb_load_other.
A statement that stores fewer rows than csdb sent stops the load
before the commit. The error has class csdb_load_other, and the
server stores no row.
A connection that cannot open before the load gives
csdb_load_transient, with the error of connect() in its
message.
A row with more than 900 MB of JSON text stops the load before csdb sends
it. PostgreSQL refuses a value of 1 GB or more. The error has class
csdb_load_other.
The field type DOUBLE creates a double precision column. Until
2026.10.16 it created real, which keeps about 7 significant digits.
DBTable_v9$create_table() changes each real column that a
table declares DOUBLE to double precision with one
ALTER TABLE, and the table keeps its rows. PostgreSQL rewrites the
table and its indexes, and blocks every other access to the table until the
rewrite ends. The ALTER waits at most 60 s for its lock, and then
stops with an error. The table then stays as it was.
configConfiguration details of the database.
connectionDatabase connection. NULL when another process opened it.
autoconnectionDatabase connection that automatically connects if possible. After a fork it opens a connection for the current process.
DBConnection_v9$new()Create a new DBConnection_v9 object.
DBConnection_v9$new( driver = NULL, server = NULL, port = NULL, db = NULL, schema = NULL, user = NULL, password = NULL, trusted_connection = NULL, sslmode = NULL, role_create_table = NULL )
driverDriver.
serverServer.
portPort.
dbDB.
schemaSchema (e.g. "dbo").
userUser.
passwordPassword.
trusted_connectionNULL or "yes".
sslmodeNULL or "require".
role_create_tableNULL or the role to take when creating tables.
A new 'DBConnection_v9' object.
DBConnection_v9$is_connected()Is the DB schema connected?
A connection that another process opened does not count. The method drops that connection first, and then reports FALSE.
DBConnection_v9$is_connected()
TRUE/FALSE.
DBConnection_v9$print()Class-specific print function.
DBConnection_v9$print(...)
...Not used.
DBConnection_v9$connect()Connect to the database.
The method drops a connection that another process opened, and then opens a connection for the current process.
The method tries again after any error, until it has made
attempts attempts. It waits 2 s before attempt 2 and 10 s
before each later attempt, as a bcp or a JSON load does. Each failed
attempt emits a message with its number, the wait and the error.
DBConnection_v9$connect(attempts = 3)
attemptsThe number of attempts to connect.
DBConnection_v9$disconnect()Disconnect from the database.
The method closes only a connection that this process opened. A connection that another process opened stays open.
DBConnection_v9$disconnect()
DBConnection_v9$clone()The objects of this class are cloneable with this method.
DBConnection_v9$clone(deep = FALSE)
deepWhether to make a deep clone.
The introduction vignette,
vignette("csdb", package = "csdb"), which creates one of these,
connects, and disconnects again.
csdb_set_auth_hook registers the function that
connect() calls after its first failed attempt.
Other database classes:
DBTable_v9
# Creating the object stores the settings. It opens no connection, # so this runs without a database server. db <- DBConnection_v9$new( driver = "PostgreSQL Unicode", server = "localhost", port = 5432, db = "mydb", user = "myuser", password = "mypass" ) db$is_connected() db # The full cycle, on SQLite. SQLite needs no server, so this block runs # anywhere. Only the driver and the db argument change for a server. # vignette("backends", package = "csdb") puts the two configurations # side by side. sqlite_db <- DBConnection_v9$new( driver = "SQLite", db = tempfile(fileext = ".sqlite") ) sqlite_db$connect() sqlite_db$is_connected() DBI::dbListTables(sqlite_db$connection) sqlite_db$disconnect() sqlite_db$is_connected() # $autoconnection opens the file again, so a read after a disconnect # still works. DBI::dbListTables(sqlite_db$autoconnection) sqlite_db$disconnect()# Creating the object stores the settings. It opens no connection, # so this runs without a database server. db <- DBConnection_v9$new( driver = "PostgreSQL Unicode", server = "localhost", port = 5432, db = "mydb", user = "myuser", password = "mypass" ) db$is_connected() db # The full cycle, on SQLite. SQLite needs no server, so this block runs # anywhere. Only the driver and the db argument change for a server. # vignette("backends", package = "csdb") puts the two configurations # side by side. sqlite_db <- DBConnection_v9$new( driver = "SQLite", db = tempfile(fileext = ".sqlite") ) sqlite_db$connect() sqlite_db$is_connected() DBI::dbListTables(sqlite_db$connection) sqlite_db$disconnect() sqlite_db$is_connected() # $autoconnection opens the file again, so a read after a disconnect # still works. DBI::dbListTables(sqlite_db$autoconnection) sqlite_db$disconnect()
A database table management class that provides operations for data manipulation, schema validation, and table administration. This class combines database connectivity with data validation and bulk operations.
The DBTable_v9 class is a database table abstraction that provides:
Core functionality:
Table creation and schema management.
Data insertion with bulk loading capabilities.
Upsert operations (insert or update).
Index management (creation, deletion).
Data validation through customizable validators.
Integration with dplyr for data queries.
Advanced features:
Automatic table creation based on field specifications.
Schema validation with custom validator functions.
Efficient bulk data loading using database-specific methods.
Index optimization for query performance.
Cross-database compatibility (SQL Server, PostgreSQL).
Data validation: The class supports custom validation functions for both field types and data contents, which ensure data integrity and schema compliance.
One object creates three kinds of thing, and each carries its own name rule.
Named table_name, in the schema that
dbconfig names.
Named
pk_<slug>_<16 hexadecimal characters>, at most 63 characters.
The rule is the index rule below, with the prefix pk_ and the
logical name pk. The table identity is the table name on SQL
Server, and schema.table on PostgreSQL. Two different tables
get two names. Schema a with table bc and schema
ab with table c therefore no longer share a name.
csdb:::pk_physical_name() returns the name for one table. SQLite
gives the key no name.
indexes
The names you write in
indexes are logical names. Each index reaches the database under
a physical name of the form ix_<slug>_<16 hexadecimal
characters>, at most 63 characters. The name carries the table
identity, so two tables in one schema that both declare ind1 get
two indexes. csdb:::index_physical_name() returns the name for
one table and one logical name.
Every constraint name and every index name is lower case. PostgreSQL folds
an unquoted identifier to lower case, and SQLite and SQL Server do not.
A lower case name therefore reads the same in the source and in every
catalogue. A DROP CONSTRAINT can quote the name or leave it
unquoted, and it finds the constraint both ways.
A table that an earlier csdb release created keeps its old constraint name,
PK_ plus the table name with every ., [ and ]
deleted. PostgreSQL stores that name in lower case. csdb does not rename
it.
An existing table gets its missing declared indexes on first use. The first
call that reaches the table looks for the physical name of each declared
index on that table. It creates each index that is absent, and nothing
else. Later calls on the same object do no index work, and a direct call
to create_table() is one of them. After remove_table() or
keep_rows_where(), the next create_table() call checks again.
Each new R process, and each new object, checks again.
A failed create gives a warning that names the table and the index. The call then continues with its read or write.
An index under an old name stays. A table that a release before 2026.10.4
indexed as ind1 then holds both ind1 and the new physical
name. csdb does not drop the old index.
The check reads pg_indexes on PostgreSQL and sqlite_master on
SQLite. On SQL Server one statement reads sys.indexes and creates
the index when it is absent. On any other backend csdb checks nothing.
dbconnectionDatabase connection.
dbconfigConfiguration details of the database.
table_nameName of the table in the database.
table_name_short_for_mssql_fully_specified_for_postgresFully specified name of the table in the database (e.g. \[db\].\[dbo\].\[table_name\]).
table_name_short_for_mssql_fully_specified_for_postgres_textFully specified name of the table in the database (e.g. \[db\].\[dbo\].\[table_name\]).
table_name_fully_specifiedFully specified name of the table in the database (e.g. \[db\].\[dbo\].\[table_name\]).
table_name_fully_specified_textFully specified name of the table in the database (e.g. \[db\].\[dbo\].\[table_name\]) as a text string.
field_typesThe types of each column in the database table (INTEGER, DOUBLE, TEXT, BOOLEAN, DATE, DATETIME).
field_types_with_lengthThe same as field_types but with (100) added to the end of all TEXT fields.
keysThe combination of variables that uniquely identify each row in the database.
keys_with_lengthThe same as keys but with (100) added to the end of all TEXT fields.
indexesA named list of vectors (generally "ind1", "ind2", etc.) that improves the speed of data retrieval operations on a database table.
validator_field_contentsA function that validates the data before it is inserted into the database.
load_folderA temporary folder that is used to write data to before inserting into the database.
censorsA named list of censors.
DBTable_v9$new()Create a new DBTable_v9 object.
DBTable_v9$new( dbconfig, table_name, field_types, keys, indexes = NULL, validator_field_types = validator_field_types_blank, validator_field_contents = validator_field_contents_blank, dbconnection = NULL )
dbconfigConfiguration details of the database (driver, server, port, db, schema, user, password, trusted_connection, sslmode, role_create_table).
table_nameName of the table in the database.
field_typesThe types of each column in the database table (INTEGER, DOUBLE, TEXT, BOOLEAN, DATE, DATETIME).
keysThe combination of these variables uniquely identifies each row of data in the table.
indexesA named list of vectors (generally "ind1", "ind2", etc.) that improves the speed of data retrieval operations on a database table.
validator_field_typesA function that validates the field_types before the DB schema is created.
validator_field_contentsA function that validates the data before it is inserted into the database.
dbconnectionAn existing DBConnection_v9 to use, or NULL.
The object borrows a supplied connection and does not own it.
disconnect() then does nothing, so the caller decides when the
connection closes. The object creates and owns a connection when this
argument is NULL. It is the last argument, because a subclass can
forward the earlier seven positionally.
A new 'DBTable_v9' object.
DBTable_v9$print()Class-specific print function.
DBTable_v9$print(...)
...Not used.
DBTable_v9$connect()Connect to the database.
DBTable_v9$connect()
DBTable_v9$disconnect()Disconnect from the database. This does nothing when the connection came
from the dbconnection argument, because the caller owns that
connection.
DBTable_v9$disconnect()
DBTable_v9$table_exists()Does the table exist?
DBTable_v9$table_exists()
DBTable_v9$create_table()Create the database table. When the table exists and its fields differ
from field_types, this drops the table with all its rows and
creates it again.
The fields differ when the names or their order differ, as
check_fields_match() compares them. Do not call this on a table
whose rows you need, unless field_types matches the table.
You rarely call this yourself. connect(), tbl() and 12
other public methods call it once per object, through the private
method lazy_creation_of_table(). 14 of the 22 public methods
therefore can drop the table.
When the table exists and its fields match, this creates each declared index that is missing. See the section "Indexes on a table that exists".
On PostgreSQL, a field type DOUBLE creates a double precision
column. A real column declared DOUBLE in a table that exists
counts as matching. It becomes double precision with one
ALTER TABLE, and the table keeps its rows. See the section
"PostgreSQL double precision" of DBConnection_v9.
DBTable_v9$create_table()
DBTable_v9$remove_table()Drop the database table.
DBTable_v9$remove_table()
DBTable_v9$insert_data()Inserts data into the database table.
DBTable_v9$insert_data( newdata, confirm_insert_via_nrow = FALSE, verbose = TRUE, load_timeout = 3600 )
newdataThe data to insert.
confirm_insert_via_nrowIf TRUE, a PostgreSQL or SQL Server load that stops on a duplicate key is upserted once instead. Otherwise the method counts the rows after the insert, and upserts when the table holds fewer rows than newdata. It stops when the table still holds fewer rows than newdata after the upsert.
verboseBoolean.
load_timeoutThe longest time in seconds that one load MAY run. On SQL Server, csdb then kills bcp and stops with an error of class csdb_load_ambiguous, and it does not retry the load. On PostgreSQL, see the section "PostgreSQL loads" of DBConnection_v9. The default of 3600 s is the 60 minutes after which Airflow kills a norsyss task.
For SQL Server and MySQL, the method writes newdata to a new load file in tempdir() for each call.
csdb deletes that file when the load returns, also after a failed load.
A write that fails partway leaves the file in tempdir(). PostgreSQL and SQLite write no file.
Called without file, the internal load methods default to a new file from tempfile().
They delete that default file in every case, also after a write that fails partway.
DBTable_v9$insert_from_tbl()Inserts the rows of the lazy table x with one
INSERT INTO ... SELECT statement. The rows never reach R.
DBTable_v9$insert_from_tbl(x)
xA lazy table (tbl_lazy) on the database of this table,
for example from $tbl() of another table.
The method supports SQLite and PostgreSQL only.
It stops before it writes when x does not read the database of
this table.
On SQLite, a different handle to the same file passes. On PostgreSQL, the
database name, server address and port MUST agree.
The statement runs on the connection of x, not on the connection
of this table. Two sessions on one database can read different rows
for one query, for example through search_path, row-level
security or a temporary table. The statement therefore copies exactly
the rows that x reads.
On SQLite, the statement names this table as main.<table>, so a
temporary table of the same name on that connection cannot receive the
rows.
It also stops when x has a column that the table lacks, or a
duplicated column.
A field that x lacks MUST have a declared type that contains
GENERATED.
The method does not run validator_field_contents, because the
rows never reach R.
The number of rows inserted, invisibly.
DBTable_v9$upsert_data()Upserts data into the database table.
DBTable_v9$upsert_data( newdata, drop_indexes = names(self$indexes), verbose = TRUE, load_timeout = 3600 )
newdataThe data to insert.
drop_indexesA vector of the indexes to drop before the upsert (can increase performance).
verboseBoolean.
load_timeoutThe longest time in seconds that one load MAY run. On SQL Server, csdb then kills bcp and stops with an error of class csdb_load_ambiguous, and it does not retry the load. On PostgreSQL, see the section "PostgreSQL loads" of DBConnection_v9. The default of 3600 s is the 60 minutes after which Airflow kills a norsyss task.
The load file follows the same rules as in insert_data(): a new file in tempdir() for each call, deleted when the load returns.
DBTable_v9$drop_all_rows()Drops all rows in the database table.
DBTable_v9$drop_all_rows()
DBTable_v9$replace_all_rows()Replaces every row of the database table with newdata, in one
transaction. When a statement fails, the table keeps its old rows.
The rows go through DBI::dbAppendTable(), not through bcp or
the JSON load. Use this method for small tables.
The method stops before any statement unless newdata has each
name in names(field_types) once, and no other column.
A change of field_types still drops and creates the table again
first, through create_table(). The first call after a schema
change can therefore start from an empty table.
DBTable_v9$replace_all_rows(newdata)
newdataThe data that replaces the rows.
DBTable_v9$drop_rows_where()Drops rows in the database table according to the SQL condition.
DBTable_v9$drop_rows_where(condition)
conditionSQL text condition.
DBTable_v9$keep_rows_where()Keeps rows in the database table according to the SQL condition.
DBTable_v9$keep_rows_where(condition)
conditionSQL text condition.
DBTable_v9$drop_all_rows_and_then_upsert_data()Drops all rows in the database table and then upserts data.
DBTable_v9$drop_all_rows_and_then_upsert_data( newdata, drop_indexes = names(self$indexes), verbose = TRUE, load_timeout = 3600 )
newdataThe data to insert.
drop_indexesA vector of the indexes to drop before the upsert (can increase performance).
verboseBoolean.
load_timeoutThe longest time in seconds that one load MAY run. On SQL Server, csdb then kills bcp and stops with an error of class csdb_load_ambiguous, and it does not retry the load. On PostgreSQL, see the section "PostgreSQL loads" of DBConnection_v9. The default of 3600 s is the 60 minutes after which Airflow kills a norsyss task.
DBTable_v9$drop_all_rows_and_then_insert_data()Drops all rows in the database table and then inserts data.
DBTable_v9$drop_all_rows_and_then_insert_data( newdata, confirm_insert_via_nrow = FALSE, verbose = TRUE, load_timeout = 3600 )
newdataThe data to insert.
confirm_insert_via_nrowIf TRUE, a PostgreSQL or SQL Server load that stops on a duplicate key is upserted once instead. Otherwise the method counts the rows after the insert, and upserts when the table holds fewer rows than newdata. It stops when the table still holds fewer rows than newdata after the upsert.
verboseBoolean.
load_timeoutThe longest time in seconds that one load MAY run. On SQL Server, csdb then kills bcp and stops with an error of class csdb_load_ambiguous, and it does not retry the load. On PostgreSQL, see the section "PostgreSQL loads" of DBConnection_v9. The default of 3600 s is the 60 minutes after which Airflow kills a norsyss task.
DBTable_v9$tbl()Provides access to the database table via dplyr::tbl.
The lazy table carries self$keys as the attribute csdb_pk.
collect_and_sort_by_pk reads it to sort the collected rows.
DBTable_v9$tbl()
DBTable_v9$print_dplyr_select()Prints a template dplyr::select call that you can copy and paste for all your variables.
DBTable_v9$print_dplyr_select()
DBTable_v9$add_indexes()Adds indexes to the database table from 'self$indexes'. Creates each index in 'self$indexes' exactly once, even when the table does not exist yet and this call is what creates it.
The names in 'self$indexes' are logical names. Each index reaches the database under a physical name. That name carries the table identity. Two tables in one schema that declare the same logical name therefore ask for different index names.
After each create, the method reads the catalogue. It raises when the index is absent from this table, and when the index covers columns other than the declared ones.
That check is defined for SQLite and for PostgreSQL, and for no other backend. On any other backend the method creates each index and does NOT verify it.
DBTable_v9$add_indexes()
DBTable_v9$drop_indexes()Drops all indexes from the database table.
The method drops the physical name that 'add_indexes()' created, for every logical name in 'self$indexes'. An index that a legacy release created under the logical name is not dropped here.
DBTable_v9$drop_indexes()
DBTable_v9$confirm_indexes()Confirms that the database holds every index declared in 'self$indexes', on this table, with the declared columns in the declared order.
The method never drops an index to reconcile. It takes one of four actions per declared index:
present with the declared columns: nothing.
absent: add it.
present with other columns: raise.
any index csdb did not name: ignore it.
The method reads an index definition on SQLite and on PostgreSQL only. On any other backend it checks the name alone, so it cannot see a change of columns.
DBTable_v9$confirm_indexes()
DBTable_v9$nrow()Gets the number of rows in the database table.
DBTable_v9$nrow(use_count = FALSE)
use_countIf TRUE, then uses the count command, which is slow but accurate. If FALSE, then uses summary statistics, which is fast but inaccurate.
DBTable_v9$info()Gets the information about the database table.
DBTable_v9$info()
DBTable_v9$clone()The objects of this class are cloneable with this method.
DBTable_v9$clone(deep = FALSE)
deepWhether to make a deep clone.
The introduction vignette,
vignette("csdb", package = "csdb"). It builds one of these on
SQLite and inserts the bundled
nor_covid19_cases_by_time_location dataset. It also shows two
tables that declare one logical index name.
DBConnection_v9 takes the same arguments as the
dbconfig list, and one is created here to hold the connection.
Other database classes:
DBConnection_v9
# Creating the object opens no connection, and the field types are # checked while it is created. These field types do not satisfy the # csfmt_rts_data_v1 schema, so the constructor stops. try(DBTable_v9$new( dbconfig = list(driver = "PostgreSQL Unicode", server = "localhost"), table_name = "my_data_table", field_types = c("id" = "INTEGER"), keys = "id", validator_field_types = validator_field_types_csfmt_rts_data_v1 )) # A full cycle on SQLite, in a file that tempfile() names. SQLite needs # no server, so this block runs anywhere. Name a driver of # "ODBC Driver 17 for SQL Server" or "PostgreSQL Unicode" instead, and # nothing else in the block changes. db_config <- list(driver = "SQLite", db = tempfile(fileext = ".sqlite")) # Indexes are named here, because add_indexes() takes no arguments and # reads them from the object. my_table <- DBTable_v9$new( dbconfig = db_config, table_name = "my_data_table", field_types = c( "id" = "INTEGER", "name" = "TEXT", "value" = "DOUBLE", "date_created" = "DATE" ), keys = "id", indexes = list("ind1" = c("name", "date_created")), validator_field_types = validator_field_types_blank, validator_field_contents = validator_field_contents_blank ) my_table$create_table() # insert_data() and upsert_data() need a data.table. my_table$insert_data(data.table::data.table( id = 1:3, name = c("Alice", "Bob", "Charlie"), value = c(10.5, 20.3, 15.7), date_created = as.Date("2023-01-01") )) # tbl() returns a lazy dbplyr reference. my_table$tbl() |> dplyr::filter(value > 15) |> dplyr::collect() # Add the indexes that were named above. my_table$add_indexes() my_table$upsert_data(data.table::data.table( id = 2:4, name = c("Bob_Updated", "Charlie", "David"), value = c(25.0, 15.7, 30.2), date_created = as.Date("2023-01-02") )) my_table$nrow() my_table$disconnect()# Creating the object opens no connection, and the field types are # checked while it is created. These field types do not satisfy the # csfmt_rts_data_v1 schema, so the constructor stops. try(DBTable_v9$new( dbconfig = list(driver = "PostgreSQL Unicode", server = "localhost"), table_name = "my_data_table", field_types = c("id" = "INTEGER"), keys = "id", validator_field_types = validator_field_types_csfmt_rts_data_v1 )) # A full cycle on SQLite, in a file that tempfile() names. SQLite needs # no server, so this block runs anywhere. Name a driver of # "ODBC Driver 17 for SQL Server" or "PostgreSQL Unicode" instead, and # nothing else in the block changes. db_config <- list(driver = "SQLite", db = tempfile(fileext = ".sqlite")) # Indexes are named here, because add_indexes() takes no arguments and # reads them from the object. my_table <- DBTable_v9$new( dbconfig = db_config, table_name = "my_data_table", field_types = c( "id" = "INTEGER", "name" = "TEXT", "value" = "DOUBLE", "date_created" = "DATE" ), keys = "id", indexes = list("ind1" = c("name", "date_created")), validator_field_types = validator_field_types_blank, validator_field_contents = validator_field_contents_blank ) my_table$create_table() # insert_data() and upsert_data() need a data.table. my_table$insert_data(data.table::data.table( id = 1:3, name = c("Alice", "Bob", "Charlie"), value = c(10.5, 20.3, 15.7), date_created = as.Date("2023-01-01") )) # tbl() returns a lazy dbplyr reference. my_table$tbl() |> dplyr::filter(value > 15) |> dplyr::collect() # Add the indexes that were named above. my_table$add_indexes() my_table$upsert_data(data.table::data.table( id = 2:4, name = c("Bob_Updated", "Charlie", "David"), value = c(25.0, 15.7, 30.2), date_created = as.Date("2023-01-02") )) my_table$nrow() my_table$disconnect()
Gets information about database tables: their names, their row counts, and their storage sizes. The function is a generic, with one method for each supported database system.
get_table_names_and_info(connection)get_table_names_and_info(connection)
connection |
A database connection object, for example from
|
A data.table containing table information with columns:
Character. Name of the table.
Numeric. The row count as the database reports it. On
PostgreSQL it is reltuples from pg_class, which is an
estimate. On Microsoft SQL Server it is the rows column of
sp_spaceused. On SQLite it is COUNT(*), which is exact
rather than an estimate.
Numeric. Total size of the table in gigabytes.
NA_real_ on SQLite.
Numeric. Size of data in gigabytes.
NA_real_ on SQLite.
Numeric. Size of indexes in gigabytes.
NA_real_ on SQLite.
SQLite reports no per-table size. The dbstat virtual table is the
only source of one. The SQLite build that RSQLite ships does not
compile dbstat in: a query against it fails with
no such table: dbstat. pragma page_count and
pragma page_size exist, but they describe the whole file rather than
one table, so all three size columns are NA_real_.
DBTable_v9, whose info() method and whose
nrow(use_count = FALSE) method call this function.
The introduction vignette,
vignette("csdb", package = "csdb"), does not mention this function.
# SQLite needs no server, so this block runs anywhere. The three size # columns are NA_real_ here, and carry a number on the other two # backends. con <- DBI::dbConnect(RSQLite::SQLite(), tempfile(fileext = ".sqlite")) DBI::dbWriteTable(con, "cases", data.frame(id = 1:3, n = c(7, 8, 9))) get_table_names_and_info(con) DBI::dbDisconnect(con) ## Not run: # A server backend needs a running server, so this block cannot run # here. Methods exist for the "PostgreSQL" and "Microsoft SQL Server" # connection classes that odbc creates. con <- DBI::dbConnect(odbc::odbc(), driver = "PostgreSQL Unicode", server = "localhost", port = 5432, database = "mydb", uid = "user", password = "pass" ) get_table_names_and_info(con) DBI::dbDisconnect(con) ## End(Not run)# SQLite needs no server, so this block runs anywhere. The three size # columns are NA_real_ here, and carry a number on the other two # backends. con <- DBI::dbConnect(RSQLite::SQLite(), tempfile(fileext = ".sqlite")) DBI::dbWriteTable(con, "cases", data.frame(id = 1:3, n = c(7, 8, 9))) get_table_names_and_info(con) DBI::dbDisconnect(con) ## Not run: # A server backend needs a running server, so this block cannot run # here. Methods exist for the "PostgreSQL" and "Microsoft SQL Server" # connection classes that odbc creates. con <- DBI::dbConnect(odbc::odbc(), driver = "PostgreSQL Unicode", server = "localhost", port = 5432, database = "mydb", uid = "user", password = "pass" ) get_table_names_and_info(con) DBI::dbDisconnect(con) ## End(Not run)
Inserts one data.table into each table of a list. On PostgreSQL, one
transaction loads every table, so by default the call stores every row or
no row. The one exception is a duplicate key with
confirm_insert_via_nrow = TRUE: csdb then inserts table by table.
insert_data_many( tables, newdata, confirm_insert_via_nrow = FALSE, verbose = TRUE, load_timeout = 3600 )insert_data_many( tables, newdata, confirm_insert_via_nrow = FALSE, verbose = TRUE, load_timeout = 3600 )
tables |
A list of |
newdata |
A list of data.tables, one for each table, in the order of
|
confirm_insert_via_nrow |
See |
verbose |
See |
load_timeout |
The longest time in seconds that the load MAY run. On
PostgreSQL, the server cancels the statement that runs past this time and
stores no row, and the error has class |
On PostgreSQL, one transaction on the connection of the first table loads
every table. csdb sends the rows as JSON text, at most 500,000 rows in one
statement, and starts no client. A table whose data.table is NULL or
has no rows gets no statement. After each statement, csdb compares the
stored rows with the rows sent. A difference raises an error before the
commit, so the server stores no row in any table.
The transaction holds a lock on every table until it commits, so a
TRUNCATE or an index change on one of them waits. The transaction
waits at most 60 s for one lock. After a longer wait, a deadlock or a
serialization failure, csdb runs the whole load again, at most 3 attempts
in total. A load whose connection breaks, or whose COMMIT fails, does not
run again. The error then says to count the rows first.
A duplicate key stops the load. With
confirm_insert_via_nrow = TRUE, csdb then calls
$insert_data(confirm_insert_via_nrow = TRUE) on each table, which
upserts a table that stops on the duplicate key.
With another driver, or with tables that have different connection settings,
csdb calls $insert_data() on each table in turn.
NULL, invisibly.
# SQLite has no JSON load, so csdb inserts into each table in turn here. db_config <- list(driver = "SQLite", db = tempfile(fileext = ".sqlite")) connection <- DBConnection_v9$new(driver = "SQLite", db = db_config$db) tables <- lapply(c("cases_a", "cases_b"), function(name) { DBTable_v9$new( dbconfig = db_config, table_name = name, field_types = c("id" = "INTEGER", "n" = "INTEGER"), keys = "id", dbconnection = connection ) }) insert_data_many( tables, list( data.table::data.table(id = 1:2, n = c(5L, 7L)), data.table::data.table(id = 1L, n = 3L) ) ) tables[[1]]$nrow() connection$disconnect()# SQLite has no JSON load, so csdb inserts into each table in turn here. db_config <- list(driver = "SQLite", db = tempfile(fileext = ".sqlite")) connection <- DBConnection_v9$new(driver = "SQLite", db = db_config$db) tables <- lapply(c("cases_a", "cases_b"), function(name) { DBTable_v9$new( dbconfig = db_config, table_name = name, field_types = c("id" = "INTEGER", "n" = "INTEGER"), keys = "id", dbconnection = connection ) }) insert_data_many( tables, list( data.table::data.table(id = 1:2, n = c(5L, 7L)), data.table::data.table(id = 1L, n = 3L) ) ) tables[[1]]$nrow() connection$disconnect()
This data comes from the Norwegian Surveillance System for Communicable Diseases (MSIS). The date corresponds to when the PCR-test was taken.
nor_covid19_cases_by_time_locationnor_covid19_cases_by_time_location
A data.table with 11028 rows and 18 variables:
day/isoweek
nation, county
nor
norge, 11 counties
2020
total
total
Isoyear of event
Isoweek of event
Isoyearweek of event
Season of event
Seasonweek of event
Calyear of event
Calmonth of event
Calyearmonth of event
Date of event
Number of confirmed covid19 cases
Number of confirmed covid19 cases per 100.000 population
The raw number of cases and cases per 100.000 population are recorded.
This data was extracted on 2022-05-04.
head(nor_covid19_cases_by_time_location) nrow(nor_covid19_cases_by_time_location)head(nor_covid19_cases_by_time_location) nrow(nor_covid19_cases_by_time_location)
Measures how far each summary of a synthetic profile is from the same summary of a real profile. It judges each distance against the sampling noise of a synthetic table of that size.
profile_compare(real, synth, margin = 0.05, n_boot = 200L, seed = 1L)profile_compare(real, synth, margin = 0.05, n_boot = 200L, seed = 1L)
real |
The |
synth |
The |
margin |
The amount by which a distance can exceed the noise of its table and still pass. |
n_boot |
The number of bootstrap draws for each table. |
seed |
The seed for |
Each row compares one summary of real with the same summary of
synth. The tables of counts are levels, days, weeks, months,
quarters, bins, crosstab and group_sizes. The distance of two
tables is the total variation distance of their shares. Each table is
normalised over its own published cells, so suppressed cells take no
part.
The function aligns the cells of the two tables first:
Ordered cells are days, weeks, months, runs of quarters, bins, ranges of group sizes, and the levels of a number or a time. Cells of the two tables that overlap join one aligned cell. So each aligned cell is a union of whole cells of both tables. It takes the coarser resolution of the two at that place. The last range of group sizes has no end.
Unordered cells are the levels of a TEXT or BOOLEAN column and the
cells of a crosstab. They align by value.
An aligned cell that only one table holds counts in the distance. Merge
suppression drops no ordered row. The simulator draws no row in a cell
that real suppressed.
The threshold of a table comes from n_boot draws:
Each draw is a multinomial sample from the real shares. Its size is
the size of the synthetic table: its rows, suppressed cells included,
or its identifiers for group_sizes.
An ordered draw puts each row at a uniform value within its real cell,
as simulate_from_profile() does.
The function applies the k merge of profile_query() to the draw,
with the k and max_levels of real. Unordered cells below k are
removed.
The threshold is the 95th percentile of the distances of the draws
from real, plus margin.
The other rows:
missing_share: the absolute difference of the two shares. The draws
are binomial, of synth$n_rows rows at the real share. The function
skips a column where either share is "suppressed".
n_distinct: 0 when the synthetic n_distinct is in the range that
synth$n_rows uniform draws from the real n_distinct values can
reach. Otherwise the absolute difference from the nearest end of that
range, divided by that end. The range runs from the expected number of
distinct values in those draws up to the smaller of the real
n_distinct and synth$n_rows. Both ends are rounded down to a
multiple of the k of synth, as the profile rounds n_distinct.
The threshold is margin.
dependency: 0 when both profiles agree on holds, otherwise 1. The
threshold is 0.
A summary of real that synth lacks, or holds in a form that does not
align, gets distance 1 and threshold margin. A schema_only column has
only its missing_share compared. The draws do not model the noise that
noise adds to a profile.
A data.table with the columns column, property, distance,
threshold and pass. pass is distance <= threshold. A crosstab or
a dependency names its columns as "a,b".
Other simulation functions:
profile_schema(),
simulate_from_profile()
d <- data.frame(sex = rep(c("female", "male"), 500)) p <- profile_data(d, c(sex = "TEXT"), columns = c(sex = "full")) sim <- simulate_from_profile(p, n = 1000) s <- profile_data(sim, c(sex = "TEXT"), columns = c(sex = "full")) profile_compare(p, s)d <- data.frame(sex = rep(c("female", "male"), 500)) p <- profile_data(d, c(sex = "TEXT"), columns = c(sex = "full")) sim <- simulate_from_profile(p, n = 1000) s <- profile_data(sim, c(sex = "TEXT"), columns = c(sex = "full")) profile_compare(p, s)
Writes d to an in-memory SQLite database and profiles it with
profile_query(). Use it to profile data that is already in R.
profile_data(d, field_types, ...)profile_data(d, field_types, ...)
d |
A data frame that holds every column of |
field_types |
A named character vector of csdb field types, as in
|
... |
Other arguments to |
A csdb_profile, as profile_query() returns it. The query
selects every column of the in-memory table profile_data.
Other profile functions:
profile_query(),
profile_table(),
read_profile(),
write_profile()
d <- data.frame( day = as.Date("2024-01-01") + rep(0:3, each = 5), cases = rep(c(2L, 7L, 9L, 12L), each = 5) ) p <- profile_data( d, field_types = c(day = "DATE", cases = "INTEGER"), columns = c(day = "full", cases = "full") ) p$columns$dayd <- data.frame( day = as.Date("2024-01-01") + rep(0:3, each = 5), cases = rep(c(2L, 7L, 9L, 12L), each = 5) ) p <- profile_data( d, field_types = c(day = "DATE", cases = "INTEGER"), columns = c(day = "full", cases = "full") ) p$columns$day
Summarises the rows of a query as a csdb_profile, under disclosure
control. Every statistic comes from an aggregate query, and the profile
keeps no count below k.
profile_query( connection, sql, columns = NULL, field_types = NULL, keys = NULL, k = 5L, noise = NULL, max_levels = 50L, group_sizes = NULL, crosstabs = NULL, dependencies = NULL, source = NULL )profile_query( connection, sql, columns = NULL, field_types = NULL, keys = NULL, k = 5L, noise = NULL, max_levels = 50L, group_sizes = NULL, crosstabs = NULL, dependencies = NULL, source = NULL )
connection |
A DBI connection, or a DBConnection_v9. For a
|
sql |
The query to profile, as one string. The function runs it as the
subquery |
columns |
A named character vector or named list that gives the
sensitivity of each column: |
field_types |
A named character vector of csdb field types: |
keys |
A character vector of key column names, or |
k |
The smallest count that the profile can hold. |
noise |
|
max_levels |
The largest number of distinct values for which a |
group_sizes |
A named list, for example |
crosstabs |
A list of pairs of column names, for example
|
dependencies |
A list of pairs of column names. For each pair the profile holds whether the first column determines the second. |
source |
A label for the data source, or |
Each column of field_types gets a summary from its sensitivity:
schema_only: type, sensitivity and missing_share. All other
summaries hold these three fields too. An INTEGER or DOUBLE column
also holds nonnegative, which is TRUE when its SQL minimum is at
least 0.
exclude: no entry in columns. The column is in field_types only.
full TEXT or BOOLEAN, at most max_levels distinct values:
levels and n.
full INTEGER, DOUBLE or DATETIME, at most max_levels distinct
values: levels and n when every level holds at least k rows.
Otherwise the column takes the summary that it has above max_levels.
An INTEGER or DOUBLE column with one distinct value always
publishes levels. When that value holds fewer than k rows, the
function removes its cell, so levels and n are empty.
full TEXT, above max_levels: n_distinct, rounded down to a
multiple of k.
full DATE: counts per day, as days and n.
full DATETIME: levels and n, as above, otherwise counts per UTC
day as days and n. The function truncates each level to the whole
second.
coarsen DATE or DATETIME: counts per ISO week, as weeks and n.
The Monday of each week is its key. A DATETIME falls in the week of
its UTC day.
INTEGER and DOUBLE, full above max_levels or coarsen: breaks
and n, for the bins [breaks[i], breaks[i + 1]). The breaks are
always double.
coarsen TEXT or BOOLEAN: an error that names the column.
The breaks come from pretty(c(min, max), n = 20). An end break that
equals the observed minimum or maximum moves one step outward. The
function removes an inner break that equals either extreme. So no break
equals an observed extreme.
Suppression keeps every published count at k or above. On an ordered
dimension, a cell below k merges with its neighbours:
Days merge into ISO weeks, then calendar months, then calendar
quarters. Weeks merge into months, then quarters. The column takes the
finest of these resolutions at which every cell holds k. The field
name gives the resolution: days, weeks, months or quarters.
Each key is the first day of its cell. A week merges into the month of
its Monday.
When a quarter holds fewer than k rows, adjacent quarters merge into
runs. Each run takes quarters in order until it holds k. A last run
below k joins the run before it. quarters then holds the first
quarter of each run and quarters_to the last.
Bins merge into runs in the same way. A merged bin keeps the outer breaks of its run, so no break is added.
Group sizes merge into runs in the same way. Each run is published as
size_from, size_to and n, the number of values with a row count
in that range. The ranges tile the row counts from 1 up with no gap.
The first range starts at 1. Every other size_from is an observed row
count, the smallest in its run. Each size_to is one below the next
size_from. The last range has no size_to, so it runs from its
size_from up.
A first run that holds only the smallest row count merges with the next run. A last run that holds only the largest merges with the run before it. So no exact smallest or largest row count is published.
A table whose present values number fewer than k publishes no cell.
Unordered cells, which are the levels of a TEXT or BOOLEAN column
and the cells of a crosstab, do not merge. Each cell below k is
removed. A column sums its removed counts into suppressed_n, and it
keeps suppressed_n only when that sum is at least k. With noise,
the function adds the noise to the finest cells, before it merges or
removes any cell.
missing_share is "suppressed" when the count of missing values, or
the count of values present, is from 1 to k - 1. n_rows holds no
noise. A query with fewer than k rows is an error.
The function reads the data with several queries. It runs them in one read snapshot where the driver gives one:
SQLite: one read transaction.
PostgreSQL: a transaction at REPEATABLE READ, READ ONLY.
SQL Server: a transaction at SNAPSHOT when the database allows it,
otherwise at REPEATABLE READ. REPEATABLE READ does not stop the
rows that other sessions insert. The function puts back the isolation
level of the session after the profile.
Other drivers, or a connection on which DBI::dbBegin() fails, for
example because a transaction is open: no snapshot, and a message says
so.
The function sends only SELECT and transaction-control statements, and
ends the transaction with a rollback.
The function always refuses a torn profile, with or without a snapshot.
The check covers each column with levels, days, weeks, months,
quarters or breaks. Its counts before noise and suppression, plus its
count of missing values, MUST equal n_rows. For a group-size column,
the row counts of its values plus its missing count MUST equal n_rows. Otherwise the function stops with an error that
names the column and both totals. A crosstab and an n_distinct have no
total to check.
A crosstab counts the rows where both columns hold a value. Each of its
columns MUST have levels or be a DATE. A group-size range is a range
of row counts, so it can be below k. Only n must reach k. A
dependency holds when each value of the first column, NULL included,
goes with one value of the second. The profile stores no mapping.
A list of class csdb_profile, with the elements provenance,
field_types, keys, n_rows, columns, group_sizes, crosstabs,
dependencies and notes. provenance holds format, source,
query, driver, profiled_at (UTC, ISO 8601), k, noise,
max_levels and csdb_version. driver is the class of the DBI
connection.
Other profile functions:
profile_data(),
profile_table(),
read_profile(),
write_profile()
con <- DBI::dbConnect(RSQLite::SQLite(), ":memory:", extended_types = TRUE) DBI::dbWriteTable(con, "visits", data.frame( id = rep(1:20, each = 3), sex = rep(c("female", "male"), 30), age = rep(c(4, 15, 38, 52, 71, 90), 10) )) p <- profile_query( con, "SELECT * FROM visits", columns = c(sex = "full", age = "coarsen", id = "exclude"), group_sizes = list(rows_per_id = "id") ) p$columns$sex p$columns$age$breaks DBI::dbDisconnect(con)con <- DBI::dbConnect(RSQLite::SQLite(), ":memory:", extended_types = TRUE) DBI::dbWriteTable(con, "visits", data.frame( id = rep(1:20, each = 3), sex = rep(c("female", "male"), 30), age = rep(c(4, 15, 38, 52, 71, 90), 10) )) p <- profile_query( con, "SELECT * FROM visits", columns = c(sex = "full", age = "coarsen", id = "exclude"), group_sizes = list(rows_per_id = "id") ) p$columns$sex p$columns$age$breaks DBI::dbDisconnect(con)
Builds a csdb_profile in which every column is schema_only. Use it with
simulate_from_profile() for a table that has no real profile.
profile_schema(field_types, keys = NULL)profile_schema(field_types, keys = NULL)
field_types |
A named character vector of csdb field types: |
keys |
A character vector of key column names, or |
A csdb_profile. Each column has type, sensitivity
"schema_only" and missing_share 0. n_rows is 0, and
provenance$source is "schema".
Other simulation functions:
profile_compare(),
simulate_from_profile()
p <- profile_schema(c(id = "INTEGER", sex = "TEXT"), keys = "id") simulate_from_profile(p, n = 5)p <- profile_schema(c(id = "INTEGER", sex = "TEXT"), keys = "id") simulate_from_profile(p, n = 5)
Profiles every row of a DBTable_v9 with profile_query(). The table
supplies the query, the field types and the keys.
profile_table(table, columns = NULL, ...)profile_table(table, columns = NULL, ...)
table |
A DBTable_v9. |
columns |
The sensitivity of each column, as in |
... |
Other arguments to |
A csdb_profile, as profile_query() returns it. The query is
dbplyr::sql_render(table$tbl()).
Other profile functions:
profile_data(),
profile_query(),
read_profile(),
write_profile()
tab <- DBTable_v9$new( dbconfig = list(driver = "SQLite", db = tempfile(fileext = ".sqlite")), table_name = "visits", field_types = c(id = "INTEGER", sex = "TEXT"), keys = "id", validator_field_types = validator_field_types_blank, validator_field_contents = validator_field_contents_blank ) tab$create_table() tab$insert_data(data.table::data.table( id = 1:12, sex = rep(c("female", "male"), 6) )) p <- profile_table(tab, columns = c(sex = "full")) p$columns$sex tab$dbconnection$disconnect()tab <- DBTable_v9$new( dbconfig = list(driver = "SQLite", db = tempfile(fileext = ".sqlite")), table_name = "visits", field_types = c(id = "INTEGER", sex = "TEXT"), keys = "id", validator_field_types = validator_field_types_blank, validator_field_contents = validator_field_contents_blank ) tab$create_table() tab$insert_data(data.table::data.table( id = 1:12, sex = rep(c("female", "male"), 6) )) p <- profile_table(tab, columns = c(sex = "full")) p$columns$sex tab$dbconnection$disconnect()
Reads a file that write_profile() wrote. The function decodes each value
by its field name and by the type of its column.
read_profile(path)read_profile(path)
path |
The YAML file to read. |
A csdb_profile. identical(read_profile(write_profile(p, f)), p)
is TRUE.
Other profile functions:
profile_data(),
profile_query(),
profile_table(),
write_profile()
d <- data.frame(day = as.Date("2024-01-01") + rep(0:1, each = 6)) p <- profile_data(d, c(day = "DATE"), columns = c(day = "full")) f <- write_profile(p, tempfile(fileext = ".yaml")) identical(read_profile(f), p)d <- data.frame(day = as.Date("2024-01-01") + rep(0:1, each = 6)) p <- profile_data(d, c(day = "DATE"), columns = c(day = "full")) f <- write_profile(p, tempfile(fileext = ".yaml")) identical(read_profile(f), p)
set_pk() attaches keys to x, so that collect_and_sort_by_pk() can
sort the result. DBTable_v9$tbl() calls it for every table. Call it for
a lazy table that you build yourself, for example from SQL text with
dplyr::sql(), when its rows have a primary key.
set_pk(x, keys)set_pk(x, keys)
x |
A lazy table. |
keys |
A character vector with the primary key columns, or |
x, with the key attached.
Other row order:
collect_and_sort_by_pk(),
setorder_by_pk()
con <- DBI::dbConnect(RSQLite::SQLite(), ":memory:") DBI::dbWriteTable(con, "t", data.frame(a = c(2L, 1L), b = c("y", "x"))) q <- set_pk(dplyr::tbl(con, dplyr::sql("SELECT a, b FROM t")), "a") collect_and_sort_by_pk(q) DBI::dbDisconnect(con)con <- DBI::dbConnect(RSQLite::SQLite(), ":memory:") DBI::dbWriteTable(con, "t", data.frame(a = c(2L, 1L), b = c("y", "x"))) q <- set_pk(dplyr::tbl(con, dplyr::sql("SELECT a, b FROM t")), "a") collect_and_sort_by_pk(q) DBI::dbDisconnect(con)
setorder_by_pk() orders d by reference. It sorts first on the primary
key columns of table, and then on every other column of d.
setorder_by_pk(d, table = NULL)setorder_by_pk(d, table = NULL)
d |
A data.table. The function changes the row order of |
table |
|
A database does not define the order of the rows that a query returns.
PostgreSQL can return the same rows in a different order on each call.
Code that reads d[1], d[.N] or tail(d, 1) after dplyr::collect()
therefore gets an arbitrary row. Call setorder_by_pk() on the result to
make that row deterministic.
The sort columns are, in this order:
the columns of table$keys that d has, in the order of table$keys.
every other column of d, in the column order of d.
The function ignores a column of table$keys that d does not have. With
table = NULL, or with table$keys equal to NULL, the function sorts on
every column of d. Each column sorts in ascending order, with NA first.
A list column or a complex column is no sort column, because
data.table::setorderv() cannot sort it.
The function matches the key by column name only. The result is always in one fixed order. It is the primary key order only while the key columns keep their names and values.
For a query that starts at DBTable_v9$tbl(), use
collect_and_sort_by_pk(). It collects and sorts in one step.
d, sorted. The return value is the same object as the argument
d, so the function works at the end of a pipe and in an assignment.
Other row order:
collect_and_sort_by_pk(),
set_pk()
d <- data.table::data.table( a = c(2L, 1L, 2L, 1L), b = c("y", "y", "x", "x"), v = c(4, 3, 2, 1) ) setorder_by_pk(d, list(keys = c("b", "a"))) d # Without a table, the function sorts on every column. setorder_by_pk(d)d <- data.table::data.table( a = c(2L, 1L, 2L, 1L), b = c("y", "y", "x", "x"), v = c(4, 3, 2, 1) ) setorder_by_pk(d, list(keys = c("b", "a"))) d # Without a table, the function sorts on every column. setorder_by_pk(d)
Draws n synthetic rows from a csdb_profile. The rows follow the
published summaries and hold no row of the profiled data.
simulate_from_profile(profile, n = 1000L, seed = 1L, world = NULL)simulate_from_profile(profile, n = 1000L, seed = 1L, world = NULL)
profile |
A |
n |
The number of rows, a whole number of at least 1. |
seed |
The seed for |
world |
|
The R type of each column follows its field type: TEXT character,
INTEGER integer, DOUBLE double, BOOLEAN logical, DATE Date and
DATETIME POSIXct in UTC.
A column takes its values from its own summary:
levels or days: a draw of the published values, weighted by n.
The suppressed cells generate nothing. A DATETIME drawn from days
gets a uniform whole second within its UTC day.
weeks, months or quarters: a cell drawn by n, then a uniform
day within it. A cell of quarters ends with the quarter in
quarters_to when the profile holds quarters_to.
breaks: a bin drawn by n, then a uniform value within the bin. An
INTEGER value is a uniform whole number within the bin. A column with
nonnegative TRUE draws no value below 0.
n_distinct of a TEXT column: "<column>_<i>", with i uniform in
1 to n_distinct.
missing_share: NA at that rate. A share of "suppressed" gives no
NA. A key column gets no NA.
A schema_only or exclude column, and a column whose summary has no
published cell, gets schema values. A TEXT or INTEGER key column gets
"<column>_<i>" or i for row i, so a single-column key is unique at
any n. Other columns get schema values by type:
TEXT: "<column>_<i>", with i from 1 to 10.
INTEGER: a whole number from 0 to 100.
DOUBLE: a uniform value from 0 to 1.
BOOLEAN: TRUE or FALSE. A BOOLEAN with n_distinct only also
gets these values.
DATE and DATETIME: a uniform day from 2020-01-01 to 2024-12-31. A
DATETIME gets a uniform whole second within that day.
The joint structure comes after the columns, in this order:
Each crosstab draws its two columns jointly by the cell counts. This replaces the values of both columns.
Each group size draws a range by n, then a uniform row count from
size_from to size_to. The last range has no size_to and draws
up to 2 * size_from. It draws row counts until they cover all rows,
gives each group a fresh identifier, and truncates the last group.
With no published range, each group has 1 row.
Each dependency that holds gives every value of its first column one value of the second column. The function assigns the values of the first column from the most rows to the fewest. Each goes to the value of the second column that is furthest below its drawn row count. This keeps the drawn frequencies of the second column close.
Before it draws, the function computes the key space. That is the
product, over the key columns, of the number of values each column can
take. When n is larger, it stops with an error that names the keys, the
key space and n. A key column can take:
a world column: its allowed values.
levels or days: the values with a count above 0. A DATETIME from
days can take every second of those days.
weeks, months or quarters: every day of the cells with a count
above 0. A DATETIME can take every second of those days.
breaks: an INTEGER takes every whole number of the bins with a
count above 0, from 0 up when nonnegative is TRUE. A DOUBLE has
no limit.
n_distinct of a TEXT column: n_distinct values.
a group-size column: no limit, because each group gets a fresh identifier.
schema values: no limit for a TEXT, INTEGER or DOUBLE key
column, and 2 for BOOLEAN. A DATE takes the 1827 days from
2020-01-01 to 2024-12-31, and a DATETIME every second of those days.
A crosstab replaces its columns, so a key column of a crosstab can take
the values that it has in the cells left after world. The key space
does not count crosstab pairs or dependencies, so it is an upper bound.
The function redraws each row whose keys repeat an earlier row. After 20
redraws it stops with an error that names the keys and n. A redrawn row
keeps the values of its group-size columns.
A world column takes its values from world only. A value that the
column's levels or days also hold keeps its published weight. Every
other value gets the mean of those weights, or all values get equal
weights when the profile holds none of them. A crosstab keeps only the
cells whose values world allows, and has no effect when no cell is left.
A group-size column takes its identifiers from world, without
replacement where world has enough values.
A data.table with n rows and the columns of
profile$field_types, in that order.
Other simulation functions:
profile_compare(),
profile_schema()
d <- data.frame( sex = rep(c("female", "male"), 10), age = rep(c(4L, 15L, 38L, 52L, 71L), 4) ) p <- profile_data( d, c(sex = "TEXT", age = "INTEGER"), columns = c(sex = "full", age = "coarsen") ) simulate_from_profile(p, n = 5, seed = 2)d <- data.frame( sex = rep(c("female", "male"), 10), age = rep(c(4L, 15L, 38L, 52L, 71L), 4) ) p <- profile_data( d, c(sex = "TEXT", age = "INTEGER"), columns = c(sex = "full", age = "coarsen") ) simulate_from_profile(p, n = 5, seed = 2)
swap_table_sql() returns the statements that drop the live table and give its name to the shadow table.
The statements also rename each index and the primary key of the shadow to the names that csdb derives for the live table.
swap_table_sql(connection, table, shadow)swap_table_sql(connection, table, shadow)
connection |
A DBI connection, used only to quote identifiers. |
table |
The live table, a |
shadow |
The shadow table, a |
The function executes nothing. The caller MUST run the statements in order and in one transaction.
The connection only quotes identifiers, so DBI::ANSI() renders the PostgreSQL text without a server.
The two tables MUST have the same driver, database and schema, identical field_types, keys and indexes, and different table names.
The function supports SQLite and PostgreSQL only.
On PostgreSQL the statements rename each index and the primary key constraint. SQLite has no statement that renames an index, so the statements drop each index of the shadow and create it under the live name.
The first statement drops the live table, and its grants with it. A column grant or a row security policy on the live table does not carry over to the shadow.
A character vector of SQL statements.
fields <- c(id = "INTEGER", x = "TEXT") cfg <- list(driver = "PostgreSQL Unicode", db = "db", schema = "public") live <- DBTable_v9$new(cfg, "live", fields, keys = "id", indexes = list(ind1 = "x")) shadow <- DBTable_v9$new(cfg, "live_new", fields, keys = "id", indexes = list(ind1 = "x")) swap_table_sql(DBI::ANSI(), live, shadow)fields <- c(id = "INTEGER", x = "TEXT") cfg <- list(driver = "PostgreSQL Unicode", db = "db", schema = "public") live <- DBTable_v9$new(cfg, "live", fields, keys = "id", indexes = list(ind1 = "x")) shadow <- DBTable_v9$new(cfg, "live_new", fields, keys = "id", indexes = list(ind1 = "x")) swap_table_sql(DBI::ANSI(), live, shadow)
Reads profile.yaml from dir when it exists, and builds a
SyntheticTable whose datasets live in dir.
synthetic_table_from_dir(dir, name, field_types, keys = NULL, ...)synthetic_table_from_dir(dir, name, field_types, keys = NULL, ...)
dir |
The directory of the table. It holds |
name |
The name of the table. |
field_types |
A named character vector of csdb field types. |
keys |
A character vector of key column names, or |
... |
Other arguments to |
dir <- tempfile() dir.create(dir) st <- synthetic_table_from_dir(dir, "people", c(id = "INTEGER"), "id") st$list_datasets()dir <- tempfile() dir.create(dir) st <- synthetic_table_from_dir(dir, "people", c(id = "INTEGER"), "id") st$list_datasets()
A SyntheticTable holds the contract of one table and its fixed synthetic
datasets. Every data.table that a SyntheticTable returns passed
$validate().
A generator is a function(profile, n, seed, world) that returns a
data.table. generator = NULL uses simulate_from_profile() on profile,
or on profile_schema() of field_types and keys when profile is
NULL. n = NULL means the generator's own size. A generator MAY then
choose its row count, for example a complete grid of series and weeks.
simulate_from_profile() gives 1000 rows for n = NULL.
$validate(d, world) checks d in this order, and stops at the first
check that fails. The error names the check.
columns: d is a data.table, and its column names and order equal
names(field_types).
types: each column has the R type of its field type. These are
TEXT character, INTEGER integer, DOUBLE double, BOOLEAN
logical, DATE Date and DATETIME POSIXct.
keys: no two rows have the same values of keys.
validator_field_contents: validator_field_contents(d) is TRUE.
invariant '<name>': each invariant returns TRUE. A character
return is the error message.
An invariant is a function(d) or a function(d, world). The class calls
an invariant with two or more formal arguments as f(d, world), and any
other invariant as f(d). $random(), $dataset() and $add_dataset()
give the invariants their world.
The directory dir holds the datasets of the table:
datasets.yaml: one entry for each recipe, with name, kind, n,
seed, description, overrides, world_md5, rows and md5. n
is empty for n = NULL. world_md5 is absent for world = NULL.
rows is the row count of the data.
handmade/<name>.csv: one handmade dataset. Each column is read as
text and converted to its field type. An empty cell is NA.
profile.yaml: optional. synthetic_table_from_dir() reads it.
$new() does not read it.
A dataset name is lower snake case. The name default is the generator
output at seed = 1 and n = 1000 or n = NULL.
The md5 of a recipe comes from tools::md5sum() of the data that
data.table::fwrite() writes with eol = "\n". The columns are in
field_types order, the rows are sorted by every column, dates are
ISO 8601 and NA is empty.
The md5 of a world comes from tools::md5sum() of the text that
yaml::as.yaml() gives for the world, written with LF line ends. The
names are sorted in C-locale order. Each value is text: a date or a
datetime in ISO 8601, any other value by as.character(). The order of
the values within a name counts. Every element of the world counts, also
an element that names no column of the table.
$dataset(name, world) regenerates a recipe with world. When the md5 of
world equals world_md5, it checks the data against the recipe. It
stops with an error that names the dataset when the row count differs
from rows, or the md5 differs from md5. For any other world, the
recipe is validated, its md5 is not checked, and a message says so. Two
NULL worlds are equal. A recipe without rows has no row check.
nameThe name of the table.
field_typesThe field types of the table.
keysThe key columns of the table.
dirThe directory of the datasets, or NULL.
SyntheticTable$new()Create a new SyntheticTable.
SyntheticTable$new( name, field_types, keys = NULL, validator_field_contents = validator_field_contents_blank, invariants = list(), profile = NULL, generator = NULL, dir = NULL )
nameThe name of the table.
field_typesA named character vector of csdb field types.
keysA character vector of key column names, or NULL.
validator_field_contentsA function of a data.table that
returns TRUE for valid contents.
invariantsA named list of function(d) or
function(d, world). Each returns TRUE, or a message that says
why d fails.
profileA csdb_profile, or NULL.
generatorA function(profile, n, seed, world) that returns a
data.table, or NULL for simulate_from_profile().
dirThe directory of the datasets, or NULL for no datasets.
SyntheticTable$validate()Check a data.table against the contract.
SyntheticTable$validate(d, world = NULL)
dA data.table.
worldNULL, or the list that each function(d, world)
invariant receives.
d, invisibly. The method stops at the first check that
fails, and the error names it.
SyntheticTable$random()Generate and validate new data.
SyntheticTable$random(n = 1000L, seed = NULL, world = NULL)
nThe number of rows, or NULL for the generator's own size.
seedThe seed. NULL draws a seed and reports it in a
message, so you can replay a failure.
worldNULL, or a list that the generator receives.
A validated data.table.
SyntheticTable$dataset()Get a fixed dataset by name.
SyntheticTable$dataset(name, world = NULL)
nameThe name of the dataset.
worldNULL, or a list that the generator receives. The md5
check runs only when the md5 of world equals the world_md5 of
the recipe.
A validated data.table.
SyntheticTable$list_datasets()List the fixed datasets.
SyntheticTable$list_datasets()
A data.table with name, kind (recipe or handmade),
n, seed and description. A handmade dataset has NA in n,
seed and description.
SyntheticTable$add_dataset()Add a recipe, its row count and its md5 to datasets.yaml.
SyntheticTable$add_dataset( name, n, seed, description, overrides = list(), world = NULL )
nameThe name of the dataset, lower snake case and new.
nThe number of rows, or NULL for the generator's own size.
seedThe seed.
descriptionOne string that says what the dataset is for.
overridesA named list that maps a column to one fixed value. The value replaces the column after generation.
worldNULL, or a list that the generator receives. The
recipe stores its md5 as world_md5.
The validated data.table, invisibly.
SyntheticTable$check_hashes()Regenerate each recipe that world made, and compare its row count
and its md5.
SyntheticTable$check_hashes(world = NULL)
worldNULL, or the world of the recipes to check.
A data.table with name and pass. pass is NA for a
recipe that another world made.
SyntheticTable$clone()The objects of this class are cloneable with this method.
SyntheticTable$clone(deep = FALSE)
deepWhether to make a deep clone.
st <- SyntheticTable$new( name = "people", field_types = c(id = "INTEGER", sex = "TEXT"), keys = "id", invariants = list( sex_known = function(d) if (all(!is.na(d$sex))) TRUE else "sex is missing." ) ) st$random(n = 5, seed = 1)st <- SyntheticTable$new( name = "people", field_types = c(id = "INTEGER", sex = "TEXT"), keys = "id", invariants = list( sex_known = function(d) if (all(!is.na(d$sex))) TRUE else "sex is missing." ) ) st$random(n = 5, seed = 1)
A pass-through validator that accepts any data without validation. Use it as a placeholder when you need no check on the data contents.
validator_field_contents_blank(data)validator_field_contents_blank(data)
data |
A data.frame or data.table containing the data to validate. |
Always returns TRUE.
The introduction vignette,
vignette("csdb", package = "csdb"), which passes this to
DBTable_v9$new() as its validator_field_contents argument.
DBTable_v9 calls the field contents validator from its
insert_data() and upsert_data() methods.
Other field contents validators:
validator_field_contents_csfmt_rts_data_v1(),
validator_field_contents_csfmt_rts_data_v2()
# This validator always returns TRUE regardless of input test_data <- data.frame(id = 1:3, name = c("A", "B", "C"), value = c(10, 20, 30)) validator_field_contents_blank(test_data) # Works with any data structure empty_data <- data.frame() validator_field_contents_blank(empty_data)# This validator always returns TRUE regardless of input test_data <- data.frame(id = 1:3, name = c("A", "B", "C"), value = c(10, 20, 30)) validator_field_contents_blank(test_data) # Works with any data structure empty_data <- data.frame() validator_field_contents_blank(empty_data)
Checks that data contents conform to the csfmt_rts_data_v1 schema specification. The validator checks the granularity_time, granularity_geo, border, sex, and date fields against the values that schema allows.
validator_field_contents_csfmt_rts_data_v1(data)validator_field_contents_csfmt_rts_data_v1(data)
data |
A data.frame or data.table containing the data to validate. |
TRUE if data is valid for csfmt_rts_data_v1, FALSE otherwise (with error attribute).
DBTable_v9, which takes this as its
validator_field_contents argument and calls it from its
insert_data() and upsert_data() methods.
The introduction vignette,
vignette("csdb", package = "csdb"), does not use this validator.
Other field contents validators:
validator_field_contents_blank(),
validator_field_contents_csfmt_rts_data_v2()
# Valid data for csfmt_rts_data_v1 (all required columns present) valid_data <- data.frame( granularity_time = c("date", "isoyearweek", "total"), granularity_geo = c("nation", "county", "municip"), border = c("2020", "2020", "2020"), sex = c("total", "total", "total"), date = as.Date(c("2020-01-01", "2020-01-08", "2020-01-01")), stringsAsFactors = FALSE ) validator_field_contents_csfmt_rts_data_v1(valid_data) # Invalid data (unrecognised granularity_geo value) invalid_data <- data.frame( granularity_time = "date", granularity_geo = "invalid_geo", border = "2020", sex = "total", date = as.Date("2020-01-01"), stringsAsFactors = FALSE ) validator_field_contents_csfmt_rts_data_v1(invalid_data)# Valid data for csfmt_rts_data_v1 (all required columns present) valid_data <- data.frame( granularity_time = c("date", "isoyearweek", "total"), granularity_geo = c("nation", "county", "municip"), border = c("2020", "2020", "2020"), sex = c("total", "total", "total"), date = as.Date(c("2020-01-01", "2020-01-08", "2020-01-01")), stringsAsFactors = FALSE ) validator_field_contents_csfmt_rts_data_v1(valid_data) # Invalid data (unrecognised granularity_geo value) invalid_data <- data.frame( granularity_time = "date", granularity_geo = "invalid_geo", border = "2020", sex = "total", date = as.Date("2020-01-01"), stringsAsFactors = FALSE ) validator_field_contents_csfmt_rts_data_v1(invalid_data)
Checks that data contents conform to the csfmt_rts_data_v2 schema specification. The validator checks the granularity_time, granularity_geo, border, sex, and date fields against the values that schema allows.
validator_field_contents_csfmt_rts_data_v2(data)validator_field_contents_csfmt_rts_data_v2(data)
data |
A data.frame or data.table containing the data to validate. |
TRUE if data is valid for csfmt_rts_data_v2, FALSE otherwise (with error attribute).
DBTable_v9, which takes this as its
validator_field_contents argument and calls it from its
insert_data() and upsert_data() methods.
The introduction vignette,
vignette("csdb", package = "csdb"), does not use this validator.
Other field contents validators:
validator_field_contents_blank(),
validator_field_contents_csfmt_rts_data_v1()
# Valid data for csfmt_rts_data_v2 (all required columns present) valid_data_v2 <- data.frame( granularity_time = c("date", "isoyearweek", "total"), granularity_geo = c("nation", "county", "municip"), border = c("2020", "2020", "2020"), sex = c("total", "total", "total"), date = as.Date(c("2020-01-01", "2020-01-08", "2020-01-01")), stringsAsFactors = FALSE ) validator_field_contents_csfmt_rts_data_v2(valid_data_v2) # Invalid data (unrecognised granularity_geo value) invalid_data_v2 <- data.frame( granularity_time = "date", granularity_geo = "invalid_geo", border = "2020", sex = "total", date = as.Date("2020-01-01"), stringsAsFactors = FALSE ) validator_field_contents_csfmt_rts_data_v2(invalid_data_v2)# Valid data for csfmt_rts_data_v2 (all required columns present) valid_data_v2 <- data.frame( granularity_time = c("date", "isoyearweek", "total"), granularity_geo = c("nation", "county", "municip"), border = c("2020", "2020", "2020"), sex = c("total", "total", "total"), date = as.Date(c("2020-01-01", "2020-01-08", "2020-01-01")), stringsAsFactors = FALSE ) validator_field_contents_csfmt_rts_data_v2(valid_data_v2) # Invalid data (unrecognised granularity_geo value) invalid_data_v2 <- data.frame( granularity_time = "date", granularity_geo = "invalid_geo", border = "2020", sex = "total", date = as.Date("2020-01-01"), stringsAsFactors = FALSE ) validator_field_contents_csfmt_rts_data_v2(invalid_data_v2)
A pass-through validator that accepts any field types without validation. Use it as a placeholder when you need no check on the field types.
validator_field_types_blank(db_field_types)validator_field_types_blank(db_field_types)
db_field_types |
A named character vector of database field types. |
Always returns TRUE.
The introduction vignette,
vignette("csdb", package = "csdb"), which passes this to
DBTable_v9$new() as its validator_field_types argument.
DBTable_v9 calls the field type validator once, while the
object is being created.
Other field type validators:
validator_field_types_csfmt_rts_data_v1(),
validator_field_types_csfmt_rts_data_v2()
# This validator always returns TRUE regardless of input field_types <- c("id" = "INTEGER", "name" = "TEXT", "date" = "DATE") validator_field_types_blank(field_types) # Works with any field types other_types <- c("value" = "DOUBLE", "status" = "BOOLEAN") validator_field_types_blank(other_types)# This validator always returns TRUE regardless of input field_types <- c("id" = "INTEGER", "name" = "TEXT", "date" = "DATE") validator_field_types_blank(field_types) # Works with any field types other_types <- c("value" = "DOUBLE", "status" = "BOOLEAN") validator_field_types_blank(other_types)
Checks that field types conform to the csfmt_rts_data_v1 schema
specification. The validator checks the first 16 entries of
db_field_types against the expected structure of that schema.
validator_field_types_csfmt_rts_data_v1(db_field_types)validator_field_types_csfmt_rts_data_v1(db_field_types)
db_field_types |
A named character vector of database field types. |
TRUE if field types are valid for csfmt_rts_data_v1, FALSE otherwise.
DBTable_v9, which takes this as its
validator_field_types argument and calls it once, while the object
is being created.
The introduction vignette,
vignette("csdb", package = "csdb"), does not use this validator.
Other field type validators:
validator_field_types_blank(),
validator_field_types_csfmt_rts_data_v2()
# Valid field types for csfmt_rts_data_v1 valid_fields <- c( "granularity_time" = "TEXT", "granularity_geo" = "TEXT", "country_iso3" = "TEXT", "location_code" = "TEXT", "border" = "INTEGER", "age" = "TEXT", "sex" = "TEXT", "isoyear" = "INTEGER", "isoweek" = "INTEGER", "isoyearweek" = "TEXT", "season" = "TEXT", "seasonweek" = "DOUBLE", "calyear" = "INTEGER", "calmonth" = "INTEGER", "calyearmonth" = "TEXT", "date" = "DATE", "cases_n" = "INTEGER" ) validator_field_types_csfmt_rts_data_v1(valid_fields) # Invalid field types (wrong structure) invalid_fields <- c("id" = "INTEGER", "name" = "TEXT") validator_field_types_csfmt_rts_data_v1(invalid_fields)# Valid field types for csfmt_rts_data_v1 valid_fields <- c( "granularity_time" = "TEXT", "granularity_geo" = "TEXT", "country_iso3" = "TEXT", "location_code" = "TEXT", "border" = "INTEGER", "age" = "TEXT", "sex" = "TEXT", "isoyear" = "INTEGER", "isoweek" = "INTEGER", "isoyearweek" = "TEXT", "season" = "TEXT", "seasonweek" = "DOUBLE", "calyear" = "INTEGER", "calmonth" = "INTEGER", "calyearmonth" = "TEXT", "date" = "DATE", "cases_n" = "INTEGER" ) validator_field_types_csfmt_rts_data_v1(valid_fields) # Invalid field types (wrong structure) invalid_fields <- c("id" = "INTEGER", "name" = "TEXT") validator_field_types_csfmt_rts_data_v1(invalid_fields)
Checks that field types conform to the csfmt_rts_data_v2 schema
specification. The validator checks the first 18 entries of
db_field_types against the expected structure of that schema.
validator_field_types_csfmt_rts_data_v2(db_field_types)validator_field_types_csfmt_rts_data_v2(db_field_types)
db_field_types |
A named character vector of database field types. |
TRUE if field types are valid for csfmt_rts_data_v2, FALSE otherwise.
DBTable_v9, which takes this as its
validator_field_types argument and calls it once, while the object
is being created.
The introduction vignette,
vignette("csdb", package = "csdb"), does not use this validator.
Other field type validators:
validator_field_types_blank(),
validator_field_types_csfmt_rts_data_v1()
# Valid field types for csfmt_rts_data_v2. The first 18 must match the # schema, which unlike v1 carries isoquarter and isoyearquarter. valid_fields_v2 <- c( "granularity_time" = "TEXT", "granularity_geo" = "TEXT", "country_iso3" = "TEXT", "location_code" = "TEXT", "border" = "INTEGER", "age" = "TEXT", "sex" = "TEXT", "isoyear" = "INTEGER", "isoweek" = "INTEGER", "isoyearweek" = "TEXT", "isoquarter" = "INTEGER", "isoyearquarter" = "TEXT", "season" = "TEXT", "seasonweek" = "DOUBLE", "calyear" = "INTEGER", "calmonth" = "INTEGER", "calyearmonth" = "TEXT", "date" = "DATE", "tag_outcome" = "TEXT", "tag_type" = "TEXT", "cases_n" = "INTEGER" ) validator_field_types_csfmt_rts_data_v2(valid_fields_v2) # The v1 layout is not valid for v2: it has no isoquarter validator_field_types_csfmt_rts_data_v2(valid_fields_v2[-c(11, 12)])# Valid field types for csfmt_rts_data_v2. The first 18 must match the # schema, which unlike v1 carries isoquarter and isoyearquarter. valid_fields_v2 <- c( "granularity_time" = "TEXT", "granularity_geo" = "TEXT", "country_iso3" = "TEXT", "location_code" = "TEXT", "border" = "INTEGER", "age" = "TEXT", "sex" = "TEXT", "isoyear" = "INTEGER", "isoweek" = "INTEGER", "isoyearweek" = "TEXT", "isoquarter" = "INTEGER", "isoyearquarter" = "TEXT", "season" = "TEXT", "seasonweek" = "DOUBLE", "calyear" = "INTEGER", "calmonth" = "INTEGER", "calyearmonth" = "TEXT", "date" = "DATE", "tag_outcome" = "TEXT", "tag_type" = "TEXT", "cases_n" = "INTEGER" ) validator_field_types_csfmt_rts_data_v2(valid_fields_v2) # The v1 layout is not valid for v2: it has no isoquarter validator_field_types_csfmt_rts_data_v2(valid_fields_v2[-c(11, 12)])
Writes a csdb_profile as YAML. read_profile() reads the file back to
an object identical to profile.
write_profile(profile, path)write_profile(profile, path)
profile |
A |
path |
The file to write. The function overwrites it. |
path, invisibly.
Other profile functions:
profile_data(),
profile_query(),
profile_table(),
read_profile()
d <- data.frame(sex = rep(c("female", "male"), 6)) p <- profile_data(d, c(sex = "TEXT"), columns = c(sex = "full")) f <- write_profile(p, tempfile(fileext = ".yaml")) cat(readLines(f), sep = "\n")d <- data.frame(sex = rep(c("female", "male"), 6)) p <- profile_data(d, c(sex = "TEXT"), columns = c(sex = "full")) f <- write_profile(p, tempfile(fileext = ".yaml")) cat(readLines(f), sep = "\n")