---
title: "Getting Started"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Getting Started}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r, include = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  output.lines = 10
)
has_duckdb <- requireNamespace("duckdb", quietly = TRUE)
knitr::opts_chunk$set(
  eval = has_duckdb && !identical(Sys.getenv("NOT_CRAN"), "false")
)
```

```{r setup}
library(dbSpatial)
```

## Introduction
This vignette demonstrates how to use the `{dbSpatial}` package to create a DuckDB database with spatial points and polygons starting from various data sources.

All code chunks below are evaluated only when the `duckdb` package is
available in the check environment.

## Creating a DuckDB connection
```{r}
# create db connection in memory
duckdb_conn = DBI::dbConnect(duckdb::duckdb(), ":memory:")
DBI::dbExecute(duckdb_conn, "SET threads = 1")
```

## Reading in spatial data from various sources

### From data.frames
```{r}
# test data
test_data = data.frame(x = 1:10, y = 1:10, id = 1:10)

# df, tbl
# specify x and y column names to cast to a point geometry
a <- dbSpatial(conn = duckdb_conn,
               name = "test_points",
               value = test_data,
               x_colName = "x",
               y_colName = "y",
               overwrite = TRUE)
a
```

### From .csv file
```{r}
# test data
test_data = data.frame(x = 1:10, y = 1:10, id = 1:10)

# write to file
test_file <- tempfile(fileext = ".csv")
write.csv(test_data, test_file, row.names = FALSE)

# load file in db
a <- dbSpatial(conn = duckdb_conn,
               name = "test_points",
               value = test_file,
               x_colName = "x",
               y_colName = "y",
               overwrite = TRUE)
a
```


### From {terra} objects: SpatVector
```{r}
# load terra package
library(terra)

# Create a SpatVector from the data.frame
dummy_spatvector <- terra::vect(test_data, geom = c("x", "y"))

# Load SpatVector in db
dbSpatial(conn = duckdb_conn,
          name = "spatVector_proxy",
          value = dummy_spatvector,
          overwrite = TRUE)
```
