mirror of
https://gitlab.dit.htwk-leipzig.de/htwk-software/htwkalender.git
synced 2025-08-10 13:43:49 +02:00
91 lines
2.2 KiB
Go
91 lines
2.2 KiB
Go
package dbx
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"github.com/neo4j/neo4j-go-driver/v5/neo4j"
|
|
"log/slog"
|
|
)
|
|
|
|
type (
|
|
DB struct {
|
|
driver neo4j.DriverWithContext
|
|
ctx context.Context
|
|
}
|
|
|
|
// Errors represents a list of errors.
|
|
Errors []error
|
|
)
|
|
|
|
func NewDB(username string, password string) *DB {
|
|
driver, err := neo4j.NewDriverWithContext("bolt://localhost:7687", neo4j.BasicAuth(username, password, ""))
|
|
if err != nil {
|
|
slog.Error("Failed to create a new driver: %v", err)
|
|
return nil
|
|
}
|
|
|
|
return &DB{
|
|
driver: driver,
|
|
ctx: context.Background(),
|
|
}
|
|
}
|
|
|
|
// Context returns the context associated with the DB instance.
|
|
// It returns nil if no context is associated.
|
|
func (db *DB) Context() context.Context {
|
|
return db.ctx
|
|
}
|
|
|
|
// Close closes the database, releasing any open resources.
|
|
func (db *DB) Close() error {
|
|
if db.driver != nil {
|
|
return db.driver.Close(db.ctx)
|
|
}
|
|
return nil
|
|
|
|
}
|
|
|
|
// Executor prepares, executes, or queries a SQL statement.
|
|
type Executor interface {
|
|
Query(query string, args ...interface{}) (*neo4j.ResultWithContext, error)
|
|
// QueryContext queries a SQL statement with the given context
|
|
QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)
|
|
// Prepare creates a prepared statement
|
|
Prepare(query string) (*sql.Stmt, error)
|
|
}
|
|
|
|
// Query represents a neo4j query that can be executed.
|
|
type Query struct {
|
|
Executor Executor
|
|
cypher, rawCypher string
|
|
}
|
|
|
|
func helloWorld(ctx context.Context, uri, username, password string) (string, error) {
|
|
driver, err := neo4j.NewDriverWithContext(uri, neo4j.BasicAuth(username, password, ""))
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
session := driver.NewSession(ctx, neo4j.SessionConfig{AccessMode: neo4j.AccessModeWrite})
|
|
|
|
greeting, err := session.ExecuteWrite(ctx, func(transaction neo4j.ManagedTransaction) (any, error) {
|
|
result, err := transaction.Run(ctx,
|
|
"CREATE (a:Greeting) SET a.message = $message RETURN a.message + ', from node ' + id(a)",
|
|
map[string]any{"message": "hello, world"})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
if result.Next(ctx) {
|
|
return result.Record().Values[0], nil
|
|
}
|
|
|
|
return nil, result.Err()
|
|
})
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
return greeting.(string), nil
|
|
}
|