## ----setup, include = FALSE---------------------------------------------------
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)
skip_vignette <- !reticulate::py_module_available("kuzu")

## ----eval=!skip_vignette------------------------------------------------------
library(kuzuR)
library(igraph)

# Create a connection
db_path <- tempfile()
con <- kuzu_connection(db_path)

# Create schema for nodes and relationships
kuzu_execute(con, paste("CREATE NODE TABLE Person(name STRING, age INT64,",
                        "PRIMARY KEY (name))"))
kuzu_execute(con, "CREATE REL TABLE Knows(FROM Person TO Person, since INT64)")

# Prepare data frames
persons_data <- data.frame(
  name = c("Alice", "Bob", "Carol"),
  age = c(35, 45, 25)
)

knows_data <- data.frame(
  from_person = c("Alice", "Bob"),
  to_person = c("Bob", "Carol"),
  since = c(2010, 2015)
)

# Load data into Kuzu
kuzu_copy_from_df(con, persons_data, "Person")
kuzu_copy_from_df(con, knows_data, "Knows")

## ----eval=!skip_vignette------------------------------------------------------
# Query to get all persons and their relationships
graph_query_result <- kuzu_execute(con, paste("MATCH (p1:Person)-[k:Knows]->",
                                              "(p2:Person) RETURN p1, p2, k"))

# Convert the Kuzu result to an igraph object
igraph_graph <- as_igraph(graph_query_result)

# Print the igraph object summary
print(igraph_graph)

V(igraph_graph)$label <- igraph::V(igraph_graph)$name
E(igraph_graph)$label <- "knows"
plot(igraph_graph)

## ----eval=!skip_vignette------------------------------------------------------
# Convert the Kuzu result to a tidygraph object
tidygraph_graph <- as_tidygraph(graph_query_result)

# Print the tidygraph object summary
print(tidygraph_graph)
plot(tidygraph_graph)

## ----eval=!skip_vignette------------------------------------------------------
library(g6R)
graph_query_result <- kuzu_execute(con, paste("MATCH (p1:Person)-[k:Knows]->",
                                              "(p2:Person) RETURN p1, p2, k"))
# Convert the Kuzu result to a g6R-compatible list
igraph_graph <- as_igraph(graph_query_result)

g6 <- g6_igraph(igraph_graph) |>
  g6_layout(d3_force_layout()) |>
  g6_options(
    animation = FALSE,
    node = list(
      style = list(
        labelText = JS("(d) => d.name")
      )
    ),
    edge = list(
      style = list(
        endArrow = TRUE,
        labelText = JS("(d) => d.data.label")
      )
    )
  ) |>
  g6_behaviors(
    zoom_canvas(),
    collapse_expand(),
    drag_canvas(),
    drag_element()
  ) |>
  g6_plugins("toolbar")


# Display the graph
g6

