knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  fig.path = "README-"
)

yg

yg implements a set of database management tools for communicating with SQLite or ODBC server such as Microsoft Azure SQL.

data.table tools:

library(yg)

X <- data.table(a = c(TRUE, FALSE, FALSE), b = c(11L, 22L, 34L))
Y <- data.table(c = c(5.80, 13.21, 34.55), d = c("a", "B", "C"))

(Z <- CJ.dt(X, Y))
X <- data.table(a = c(TRUE, FALSE, FALSE), b = c(11L, NA_integer_, 34L))
Y <- data.table(c = c(5.80, 13.21, NA_real_), d = c("a", NA_character_, "C"))

(Z <- CJ.dt(X, Y))

dtFillNA(dt = Z, fillNA = 34.54, fillNA_I = 23L, fillNA_C = "b")
# dtRfrhTb

# master table (dHist): fulfillment center code (fcc), stock keeping unit (sku), 
# begin quantity (bgn), end quantity (end), and sales as shipped quantity (spt).
# note: bgn != end + spt because change in inventory such as new stock comes in, 
# write off and etc. can often happen.

set.seed(285714L)

(dHist <- data.table(
  fcc = c(rep("NJ", 3L), rep("TX", 4L)),
  sku = c(paste0("A", 1L:3L), paste0("A", 1L:4L)),
  bgn = sample(40L, 7L),
  end = sample(20L, 7L),
  spt = sample(10L, 7L)
))

# refresh master table with new day sale and inventory change data - day by day.
# sale and inventory might not match as order - packing - shipping in processing

(dSale <- data.table(
  fcc = c("NJ", "NJ", "TX", "TX"),
  sku = c("A1", "A4", "A1", "A4"),
  spt = c(1L, 2L, 3L, 4L)
))

(dInvt <- data.table(
  fcc = c("NJ", "NJ", "TX", "TX"),
  sku = c("A1", "A4", "A4", "A5"),
  bgn = sample(10L, 4L),
  end = sample(10L, 4L)
))

# refresh master tbl: use fcc and sku together as id when id nomatch set vd to 0 
# as no sale, and when id nofound in dt (dHist) will be added as new sku in fcc.

(dHist <- dtRfrhTb(
  dt = dHist, tb = dSale, id = c("fcc", "sku"), vd = "spt", 
  nomatch = 0L, nofound = TRUE, in_situ = TRUE
))

(dHist <- dtRfrhTb(
  dt = dHist, tb = dInvt, id = c("fcc", "sku"), vd = c("bgn", "end"),
  nomatch = NULL, nofound = TRUE, in_situ = TRUE
))

dtFillNA(dt = dHist, fillNA = 0)

sqlite_<> tools:

sqodbc_<> tools:

# sqodbc db list prototype

sqodbc_dblist <-function() {

  list(

    # dsn = 'databaseSeverNameInWinODBC',

    srv = 'one-sql.database.windows.net',

    usr = 'username',

    pwd = 'password',

    dbn = 'database-in-sql-server'

  )

}

sqodbc_dblist_with_winAuth <-function() {

  list(

    # dsn = 'databaseSeverNameInWinODBC',

    srv = 'one-sql.database.windows.net',

    dbn = 'database-in-sql-server',

    winAuth = TRUE

  )

}


# list all tables in database in sql-server
sqodbc_executeqy(
  qy = "select * from INFORMATION_SCHEMA.TABLES", db = sqodbc_dblist()
)

# use windows authentication for connection
sqodbc_executeqy(
  qy = "select * from INFORMATION_SCHEMA.TABLES", db = sqodbc_dblist_with_winAuth()
)

bcp tools - often much faster than sqodbc_<> equivalents:



gyang274/yg documentation built on May 17, 2019, 9:42 a.m.