mirror of
https://github.com/pikami/cosmium.git
synced 2026-01-25 12:22:57 +00:00
Compare commits
15 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f5b8453995 | ||
|
|
928ca29fe4 | ||
|
|
39cd9e2357 | ||
|
|
bcf4b513b6 | ||
|
|
363f822e5a | ||
|
|
be7a615931 | ||
|
|
83f086a2dc | ||
|
|
777034181f | ||
|
|
84c33e3c8e | ||
|
|
5e677431a3 | ||
|
|
a4659d90a9 | ||
|
|
503e6bb8ad | ||
|
|
e5ddc143f0 | ||
|
|
66ea859f34 | ||
|
|
3584f9b5ce |
30
.github/workflows/compile-shared-libraries.yml
vendored
Normal file
30
.github/workflows/compile-shared-libraries.yml
vendored
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
name: Cross-Compile Shared Libraries
|
||||||
|
|
||||||
|
on:
|
||||||
|
workflow_dispatch:
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Checkout code
|
||||||
|
uses: actions/checkout@v3
|
||||||
|
|
||||||
|
- name: Cross-Compile with xgo
|
||||||
|
uses: crazy-max/ghaction-xgo@v3.1.0
|
||||||
|
with:
|
||||||
|
xgo_version: latest
|
||||||
|
go_version: 1.22.0
|
||||||
|
dest: dist
|
||||||
|
pkg: sharedlibrary
|
||||||
|
prefix: cosmium
|
||||||
|
targets: linux/amd64,linux/arm64,windows/amd64,windows/arm64,darwin/amd64,darwin/arm64
|
||||||
|
v: true
|
||||||
|
buildmode: c-shared
|
||||||
|
|
||||||
|
- name: Upload artifact
|
||||||
|
uses: actions/upload-artifact@v3
|
||||||
|
with:
|
||||||
|
name: shared-libraries
|
||||||
|
path: dist/*
|
||||||
2
.github/workflows/release.yml
vendored
2
.github/workflows/release.yml
vendored
@@ -20,7 +20,7 @@ jobs:
|
|||||||
- name: Set up Go
|
- name: Set up Go
|
||||||
uses: actions/setup-go@v5
|
uses: actions/setup-go@v5
|
||||||
with:
|
with:
|
||||||
go-version: 1.21.6
|
go-version: 1.22.0
|
||||||
- name: Docker Login
|
- name: Docker Login
|
||||||
uses: docker/login-action@v3
|
uses: docker/login-action@v3
|
||||||
with:
|
with:
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
builds:
|
builds:
|
||||||
- binary: cosmium
|
- binary: cosmium
|
||||||
|
main: ./cmd/server
|
||||||
goos:
|
goos:
|
||||||
- darwin
|
- darwin
|
||||||
- linux
|
- linux
|
||||||
@@ -9,11 +10,6 @@ builds:
|
|||||||
- arm64
|
- arm64
|
||||||
env:
|
env:
|
||||||
- CGO_ENABLED=0
|
- CGO_ENABLED=0
|
||||||
ignore:
|
|
||||||
- goos: linux
|
|
||||||
goarch: arm64
|
|
||||||
- goos: windows
|
|
||||||
goarch: arm64
|
|
||||||
|
|
||||||
release:
|
release:
|
||||||
prerelease: auto
|
prerelease: auto
|
||||||
@@ -32,11 +28,14 @@ brews:
|
|||||||
email: git@pikami.org
|
email: git@pikami.org
|
||||||
|
|
||||||
dockers:
|
dockers:
|
||||||
- image_templates:
|
- id: docker-linux-amd64
|
||||||
- "ghcr.io/pikami/{{ .ProjectName }}:{{ .Version }}"
|
goos: linux
|
||||||
- "ghcr.io/pikami/{{ .ProjectName }}:latest"
|
goarch: amd64
|
||||||
|
image_templates:
|
||||||
|
- "ghcr.io/pikami/{{ .ProjectName }}:{{ .Version }}-amd64"
|
||||||
|
- "ghcr.io/pikami/{{ .ProjectName }}:latest-amd64"
|
||||||
dockerfile: Dockerfile
|
dockerfile: Dockerfile
|
||||||
use: docker
|
use: buildx
|
||||||
build_flag_templates:
|
build_flag_templates:
|
||||||
- "--platform=linux/amd64"
|
- "--platform=linux/amd64"
|
||||||
- "--pull"
|
- "--pull"
|
||||||
@@ -47,6 +46,38 @@ dockers:
|
|||||||
- "--label=org.opencontainers.image.created={{.Date}}"
|
- "--label=org.opencontainers.image.created={{.Date}}"
|
||||||
- "--label=org.opencontainers.image.revision={{.FullCommit}}"
|
- "--label=org.opencontainers.image.revision={{.FullCommit}}"
|
||||||
- "--label=org.opencontainers.image.version={{.Version}}"
|
- "--label=org.opencontainers.image.version={{.Version}}"
|
||||||
|
- id: docker-linux-arm64
|
||||||
|
goos: linux
|
||||||
|
goarch: arm64
|
||||||
|
image_templates:
|
||||||
|
- "ghcr.io/pikami/{{ .ProjectName }}:{{ .Version }}-arm64"
|
||||||
|
- "ghcr.io/pikami/{{ .ProjectName }}:latest-arm64"
|
||||||
|
- "ghcr.io/pikami/{{ .ProjectName }}:{{ .Version }}-arm64v8"
|
||||||
|
- "ghcr.io/pikami/{{ .ProjectName }}:latest-arm64v8"
|
||||||
|
dockerfile: Dockerfile
|
||||||
|
use: buildx
|
||||||
|
build_flag_templates:
|
||||||
|
- "--platform=linux/arm64"
|
||||||
|
- "--pull"
|
||||||
|
- "--label=org.opencontainers.image.title={{.ProjectName}}"
|
||||||
|
- "--label=org.opencontainers.image.description=Lightweight Cosmos DB emulator"
|
||||||
|
- "--label=org.opencontainers.image.url=https://github.com/pikami/cosmium"
|
||||||
|
- "--label=org.opencontainers.image.source=https://github.com/pikami/cosmium"
|
||||||
|
- "--label=org.opencontainers.image.created={{.Date}}"
|
||||||
|
- "--label=org.opencontainers.image.revision={{.FullCommit}}"
|
||||||
|
- "--label=org.opencontainers.image.version={{.Version}}"
|
||||||
|
|
||||||
|
docker_manifests:
|
||||||
|
- name_template: 'ghcr.io/pikami/{{ .ProjectName }}:latest'
|
||||||
|
image_templates:
|
||||||
|
- "ghcr.io/pikami/{{ .ProjectName }}:latest-amd64"
|
||||||
|
- "ghcr.io/pikami/{{ .ProjectName }}:latest-arm64"
|
||||||
|
- "ghcr.io/pikami/{{ .ProjectName }}:latest-arm64v8"
|
||||||
|
- name_template: 'ghcr.io/pikami/{{ .ProjectName }}:{{ .Version }}'
|
||||||
|
image_templates:
|
||||||
|
- "ghcr.io/pikami/{{ .ProjectName }}:{{ .Version }}-amd64"
|
||||||
|
- "ghcr.io/pikami/{{ .ProjectName }}:{{ .Version }}-arm64"
|
||||||
|
- "ghcr.io/pikami/{{ .ProjectName }}:{{ .Version }}-arm64v8"
|
||||||
|
|
||||||
checksum:
|
checksum:
|
||||||
name_template: 'checksums.txt'
|
name_template: 'checksums.txt'
|
||||||
|
|||||||
47
Makefile
47
Makefile
@@ -4,28 +4,65 @@ GOTEST=$(GOCMD) test
|
|||||||
GOCLEAN=$(GOCMD) clean
|
GOCLEAN=$(GOCMD) clean
|
||||||
|
|
||||||
BINARY_NAME=cosmium
|
BINARY_NAME=cosmium
|
||||||
|
SERVER_LOCATION=./cmd/server
|
||||||
|
|
||||||
|
SHARED_LIB_LOCATION=./sharedlibrary
|
||||||
|
SHARED_LIB_OPT=-buildmode=c-shared
|
||||||
|
XGO_TARGETS=linux/amd64,linux/arm64,windows/amd64,windows/arm64,darwin/amd64,darwin/arm64
|
||||||
|
GOVERSION=1.22.0
|
||||||
|
|
||||||
DIST_DIR=dist
|
DIST_DIR=dist
|
||||||
|
|
||||||
|
SHARED_LIB_TEST_CC=gcc
|
||||||
|
SHARED_LIB_TEST_CFLAGS=-Wall -ldl
|
||||||
|
SHARED_LIB_TEST_TARGET=$(DIST_DIR)/sharedlibrary_test
|
||||||
|
SHARED_LIB_TEST_DIR=./sharedlibrary/tests
|
||||||
|
SHARED_LIB_TEST_SOURCES=$(wildcard $(SHARED_LIB_TEST_DIR)/*.c)
|
||||||
|
|
||||||
all: test build-all
|
all: test build-all
|
||||||
|
|
||||||
build-all: build-darwin-arm64 build-darwin-amd64 build-linux-amd64 build-windows-amd64
|
build-all: build-darwin-arm64 build-darwin-amd64 build-linux-amd64 build-linux-arm64 build-windows-amd64 build-windows-arm64
|
||||||
|
|
||||||
build-darwin-arm64:
|
build-darwin-arm64:
|
||||||
@echo "Building macOS ARM binary..."
|
@echo "Building macOS ARM binary..."
|
||||||
@GOOS=darwin GOARCH=arm64 $(GOBUILD) -o $(DIST_DIR)/$(BINARY_NAME)-darwin-arm64 .
|
@GOOS=darwin GOARCH=arm64 $(GOBUILD) -o $(DIST_DIR)/$(BINARY_NAME)-darwin-arm64 $(SERVER_LOCATION)
|
||||||
|
|
||||||
build-darwin-amd64:
|
build-darwin-amd64:
|
||||||
@echo "Building macOS x64 binary..."
|
@echo "Building macOS x64 binary..."
|
||||||
@GOOS=darwin GOARCH=amd64 $(GOBUILD) -o $(DIST_DIR)/$(BINARY_NAME)-darwin-amd64 .
|
@GOOS=darwin GOARCH=amd64 $(GOBUILD) -o $(DIST_DIR)/$(BINARY_NAME)-darwin-amd64 $(SERVER_LOCATION)
|
||||||
|
|
||||||
build-linux-amd64:
|
build-linux-amd64:
|
||||||
@echo "Building Linux x64 binary..."
|
@echo "Building Linux x64 binary..."
|
||||||
@GOOS=linux GOARCH=amd64 $(GOBUILD) -o $(DIST_DIR)/$(BINARY_NAME)-linux-amd64 .
|
@GOOS=linux GOARCH=amd64 $(GOBUILD) -o $(DIST_DIR)/$(BINARY_NAME)-linux-amd64 $(SERVER_LOCATION)
|
||||||
|
|
||||||
|
build-linux-arm64:
|
||||||
|
@echo "Building Linux ARM binary..."
|
||||||
|
@GOOS=linux GOARCH=arm64 $(GOBUILD) -o $(DIST_DIR)/$(BINARY_NAME)-linux-arm64 $(SERVER_LOCATION)
|
||||||
|
|
||||||
build-windows-amd64:
|
build-windows-amd64:
|
||||||
@echo "Building Windows x64 binary..."
|
@echo "Building Windows x64 binary..."
|
||||||
@GOOS=windows GOARCH=amd64 $(GOBUILD) -o $(DIST_DIR)/$(BINARY_NAME)-windows-amd64.exe .
|
@GOOS=windows GOARCH=amd64 $(GOBUILD) -o $(DIST_DIR)/$(BINARY_NAME)-windows-amd64.exe $(SERVER_LOCATION)
|
||||||
|
|
||||||
|
build-windows-arm64:
|
||||||
|
@echo "Building Windows ARM binary..."
|
||||||
|
@GOOS=windows GOARCH=arm64 $(GOBUILD) -o $(DIST_DIR)/$(BINARY_NAME)-windows-arm64.exe $(SERVER_LOCATION)
|
||||||
|
|
||||||
|
build-sharedlib-linux-amd64:
|
||||||
|
@echo "Building shared library for Linux x64..."
|
||||||
|
@GOOS=linux GOARCH=amd64 $(GOBUILD) $(SHARED_LIB_OPT) -o $(DIST_DIR)/$(BINARY_NAME)-linux-amd64.so $(SHARED_LIB_LOCATION)
|
||||||
|
|
||||||
|
build-sharedlib-tests: build-sharedlib-linux-amd64
|
||||||
|
@echo "Building shared library tests..."
|
||||||
|
@$(SHARED_LIB_TEST_CC) $(SHARED_LIB_TEST_CFLAGS) -o $(SHARED_LIB_TEST_TARGET) $(SHARED_LIB_TEST_SOURCES)
|
||||||
|
|
||||||
|
run-sharedlib-tests: build-sharedlib-tests
|
||||||
|
@echo "Running shared library tests..."
|
||||||
|
@$(SHARED_LIB_TEST_TARGET) $(DIST_DIR)/$(BINARY_NAME)-linux-amd64.so
|
||||||
|
|
||||||
|
xgo-compile-sharedlib:
|
||||||
|
@echo "Building shared libraries using xgo..."
|
||||||
|
@mkdir -p $(DIST_DIR)
|
||||||
|
@xgo -targets=$(XGO_TARGETS) -go $(GOVERSION) -buildmode=c-shared -dest=$(DIST_DIR) -out=$(BINARY_NAME) -pkg=$(SHARED_LIB_LOCATION) .
|
||||||
|
|
||||||
generate-parser-nosql:
|
generate-parser-nosql:
|
||||||
pigeon -o ./parsers/nosql/nosql.go ./parsers/nosql/nosql.peg
|
pigeon -o ./parsers/nosql/nosql.go ./parsers/nosql/nosql.peg
|
||||||
|
|||||||
@@ -26,9 +26,11 @@ You can download the latest version of Cosmium from the [GitHub Releases page](h
|
|||||||
Cosmium is available for the following platforms:
|
Cosmium is available for the following platforms:
|
||||||
|
|
||||||
- **Linux**: cosmium-linux-amd64
|
- **Linux**: cosmium-linux-amd64
|
||||||
|
- **Linux on ARM**: cosmium-linux-arm64
|
||||||
- **macOS**: cosmium-darwin-amd64
|
- **macOS**: cosmium-darwin-amd64
|
||||||
- **macOS on Apple Silicon**: cosmium-darwin-arm64
|
- **macOS on Apple Silicon**: cosmium-darwin-arm64
|
||||||
- **Windows**: cosmium-windows-amd64.exe
|
- **Windows**: cosmium-windows-amd64.exe
|
||||||
|
- **Windows on ARM**: cosmium-windows-arm64.exe
|
||||||
|
|
||||||
### Running Cosmium
|
### Running Cosmium
|
||||||
|
|
||||||
|
|||||||
35
api/api_server.go
Normal file
35
api/api_server.go
Normal file
@@ -0,0 +1,35 @@
|
|||||||
|
package api
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"github.com/pikami/cosmium/api/config"
|
||||||
|
"github.com/pikami/cosmium/internal/repositories"
|
||||||
|
)
|
||||||
|
|
||||||
|
type ApiServer struct {
|
||||||
|
stopServer chan interface{}
|
||||||
|
isActive bool
|
||||||
|
router *gin.Engine
|
||||||
|
config config.ServerConfig
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewApiServer(dataRepository *repositories.DataRepository, config config.ServerConfig) *ApiServer {
|
||||||
|
stopChan := make(chan interface{})
|
||||||
|
|
||||||
|
apiServer := &ApiServer{
|
||||||
|
stopServer: stopChan,
|
||||||
|
config: config,
|
||||||
|
}
|
||||||
|
|
||||||
|
apiServer.CreateRouter(dataRepository)
|
||||||
|
|
||||||
|
return apiServer
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *ApiServer) GetRouter() *gin.Engine {
|
||||||
|
return s.router
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *ApiServer) Stop() {
|
||||||
|
s.stopServer <- true
|
||||||
|
}
|
||||||
@@ -5,6 +5,8 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"os"
|
"os"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
|
"github.com/pikami/cosmium/internal/logger"
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
@@ -13,9 +15,7 @@ const (
|
|||||||
ExplorerBaseUrlLocation = "/_explorer"
|
ExplorerBaseUrlLocation = "/_explorer"
|
||||||
)
|
)
|
||||||
|
|
||||||
var Config = ServerConfig{}
|
func ParseFlags() ServerConfig {
|
||||||
|
|
||||||
func ParseFlags() {
|
|
||||||
host := flag.String("Host", "localhost", "Hostname")
|
host := flag.String("Host", "localhost", "Hostname")
|
||||||
port := flag.Int("Port", 8081, "Listen port")
|
port := flag.Int("Port", 8081, "Listen port")
|
||||||
explorerPath := flag.String("ExplorerDir", "", "Path to cosmos-explorer files")
|
explorerPath := flag.String("ExplorerDir", "", "Path to cosmos-explorer files")
|
||||||
@@ -31,22 +31,42 @@ func ParseFlags() {
|
|||||||
flag.Parse()
|
flag.Parse()
|
||||||
setFlagsFromEnvironment()
|
setFlagsFromEnvironment()
|
||||||
|
|
||||||
Config.Host = *host
|
config := ServerConfig{}
|
||||||
Config.Port = *port
|
config.Host = *host
|
||||||
Config.ExplorerPath = *explorerPath
|
config.Port = *port
|
||||||
Config.TLS_CertificatePath = *tlsCertificatePath
|
config.ExplorerPath = *explorerPath
|
||||||
Config.TLS_CertificateKey = *tlsCertificateKey
|
config.TLS_CertificatePath = *tlsCertificatePath
|
||||||
Config.InitialDataFilePath = *initialDataPath
|
config.TLS_CertificateKey = *tlsCertificateKey
|
||||||
Config.PersistDataFilePath = *persistDataPath
|
config.InitialDataFilePath = *initialDataPath
|
||||||
Config.DisableAuth = *disableAuthentication
|
config.PersistDataFilePath = *persistDataPath
|
||||||
Config.DisableTls = *disableTls
|
config.DisableAuth = *disableAuthentication
|
||||||
Config.Debug = *debug
|
config.DisableTls = *disableTls
|
||||||
|
config.Debug = *debug
|
||||||
|
config.AccountKey = *accountKey
|
||||||
|
|
||||||
Config.DatabaseAccount = Config.Host
|
config.PopulateCalculatedFields()
|
||||||
Config.DatabaseDomain = Config.Host
|
|
||||||
Config.DatabaseEndpoint = fmt.Sprintf("https://%s:%d/", Config.Host, Config.Port)
|
return config
|
||||||
Config.AccountKey = *accountKey
|
}
|
||||||
Config.ExplorerBaseUrlLocation = ExplorerBaseUrlLocation
|
|
||||||
|
func (c *ServerConfig) PopulateCalculatedFields() {
|
||||||
|
c.DatabaseAccount = c.Host
|
||||||
|
c.DatabaseDomain = c.Host
|
||||||
|
c.DatabaseEndpoint = fmt.Sprintf("https://%s:%d/", c.Host, c.Port)
|
||||||
|
c.ExplorerBaseUrlLocation = ExplorerBaseUrlLocation
|
||||||
|
logger.EnableDebugOutput = c.Debug
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *ServerConfig) ApplyDefaultsToEmptyFields() {
|
||||||
|
if c.Host == "" {
|
||||||
|
c.Host = "localhost"
|
||||||
|
}
|
||||||
|
if c.Port == 0 {
|
||||||
|
c.Port = 8081
|
||||||
|
}
|
||||||
|
if c.AccountKey == "" {
|
||||||
|
c.AccountKey = DefaultAccountKey
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func setFlagsFromEnvironment() (err error) {
|
func setFlagsFromEnvironment() (err error) {
|
||||||
|
|||||||
@@ -1,20 +1,20 @@
|
|||||||
package config
|
package config
|
||||||
|
|
||||||
type ServerConfig struct {
|
type ServerConfig struct {
|
||||||
DatabaseAccount string
|
DatabaseAccount string `json:"databaseAccount"`
|
||||||
DatabaseDomain string
|
DatabaseDomain string `json:"databaseDomain"`
|
||||||
DatabaseEndpoint string
|
DatabaseEndpoint string `json:"databaseEndpoint"`
|
||||||
AccountKey string
|
AccountKey string `json:"accountKey"`
|
||||||
|
|
||||||
ExplorerPath string
|
ExplorerPath string `json:"explorerPath"`
|
||||||
Port int
|
Port int `json:"port"`
|
||||||
Host string
|
Host string `json:"host"`
|
||||||
TLS_CertificatePath string
|
TLS_CertificatePath string `json:"tlsCertificatePath"`
|
||||||
TLS_CertificateKey string
|
TLS_CertificateKey string `json:"tlsCertificateKey"`
|
||||||
InitialDataFilePath string
|
InitialDataFilePath string `json:"initialDataFilePath"`
|
||||||
PersistDataFilePath string
|
PersistDataFilePath string `json:"persistDataFilePath"`
|
||||||
DisableAuth bool
|
DisableAuth bool `json:"disableAuth"`
|
||||||
DisableTls bool
|
DisableTls bool `json:"disableTls"`
|
||||||
Debug bool
|
Debug bool `json:"debug"`
|
||||||
ExplorerBaseUrlLocation string
|
ExplorerBaseUrlLocation string `json:"explorerBaseUrlLocation"`
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,16 +5,15 @@ import (
|
|||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
"github.com/pikami/cosmium/internal/repositories"
|
|
||||||
repositorymodels "github.com/pikami/cosmium/internal/repository_models"
|
repositorymodels "github.com/pikami/cosmium/internal/repository_models"
|
||||||
)
|
)
|
||||||
|
|
||||||
func GetAllCollections(c *gin.Context) {
|
func (h *Handlers) GetAllCollections(c *gin.Context) {
|
||||||
databaseId := c.Param("databaseId")
|
databaseId := c.Param("databaseId")
|
||||||
|
|
||||||
collections, status := repositories.GetAllCollections(databaseId)
|
collections, status := h.repository.GetAllCollections(databaseId)
|
||||||
if status == repositorymodels.StatusOk {
|
if status == repositorymodels.StatusOk {
|
||||||
database, _ := repositories.GetDatabase(databaseId)
|
database, _ := h.repository.GetDatabase(databaseId)
|
||||||
|
|
||||||
c.Header("x-ms-item-count", fmt.Sprintf("%d", len(collections)))
|
c.Header("x-ms-item-count", fmt.Sprintf("%d", len(collections)))
|
||||||
c.IndentedJSON(http.StatusOK, gin.H{
|
c.IndentedJSON(http.StatusOK, gin.H{
|
||||||
@@ -28,11 +27,11 @@ func GetAllCollections(c *gin.Context) {
|
|||||||
c.IndentedJSON(http.StatusInternalServerError, gin.H{"message": "Unknown error"})
|
c.IndentedJSON(http.StatusInternalServerError, gin.H{"message": "Unknown error"})
|
||||||
}
|
}
|
||||||
|
|
||||||
func GetCollection(c *gin.Context) {
|
func (h *Handlers) GetCollection(c *gin.Context) {
|
||||||
databaseId := c.Param("databaseId")
|
databaseId := c.Param("databaseId")
|
||||||
id := c.Param("collId")
|
id := c.Param("collId")
|
||||||
|
|
||||||
collection, status := repositories.GetCollection(databaseId, id)
|
collection, status := h.repository.GetCollection(databaseId, id)
|
||||||
if status == repositorymodels.StatusOk {
|
if status == repositorymodels.StatusOk {
|
||||||
c.IndentedJSON(http.StatusOK, collection)
|
c.IndentedJSON(http.StatusOK, collection)
|
||||||
return
|
return
|
||||||
@@ -46,11 +45,11 @@ func GetCollection(c *gin.Context) {
|
|||||||
c.IndentedJSON(http.StatusInternalServerError, gin.H{"message": "Unknown error"})
|
c.IndentedJSON(http.StatusInternalServerError, gin.H{"message": "Unknown error"})
|
||||||
}
|
}
|
||||||
|
|
||||||
func DeleteCollection(c *gin.Context) {
|
func (h *Handlers) DeleteCollection(c *gin.Context) {
|
||||||
databaseId := c.Param("databaseId")
|
databaseId := c.Param("databaseId")
|
||||||
id := c.Param("collId")
|
id := c.Param("collId")
|
||||||
|
|
||||||
status := repositories.DeleteCollection(databaseId, id)
|
status := h.repository.DeleteCollection(databaseId, id)
|
||||||
if status == repositorymodels.StatusOk {
|
if status == repositorymodels.StatusOk {
|
||||||
c.Status(http.StatusNoContent)
|
c.Status(http.StatusNoContent)
|
||||||
return
|
return
|
||||||
@@ -64,7 +63,7 @@ func DeleteCollection(c *gin.Context) {
|
|||||||
c.IndentedJSON(http.StatusInternalServerError, gin.H{"message": "Unknown error"})
|
c.IndentedJSON(http.StatusInternalServerError, gin.H{"message": "Unknown error"})
|
||||||
}
|
}
|
||||||
|
|
||||||
func CreateCollection(c *gin.Context) {
|
func (h *Handlers) CreateCollection(c *gin.Context) {
|
||||||
databaseId := c.Param("databaseId")
|
databaseId := c.Param("databaseId")
|
||||||
var newCollection repositorymodels.Collection
|
var newCollection repositorymodels.Collection
|
||||||
|
|
||||||
@@ -78,7 +77,7 @@ func CreateCollection(c *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
createdCollection, status := repositories.CreateCollection(databaseId, newCollection)
|
createdCollection, status := h.repository.CreateCollection(databaseId, newCollection)
|
||||||
if status == repositorymodels.Conflict {
|
if status == repositorymodels.Conflict {
|
||||||
c.IndentedJSON(http.StatusConflict, gin.H{"message": "Conflict"})
|
c.IndentedJSON(http.StatusConflict, gin.H{"message": "Conflict"})
|
||||||
return
|
return
|
||||||
|
|||||||
@@ -4,9 +4,14 @@ import (
|
|||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
"github.com/pikami/cosmium/internal/repositories"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func CosmiumExport(c *gin.Context) {
|
func (h *Handlers) CosmiumExport(c *gin.Context) {
|
||||||
c.IndentedJSON(http.StatusOK, repositories.GetState())
|
repositoryState, err := h.repository.GetState()
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.Data(http.StatusOK, "application/json", []byte(repositoryState))
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,12 +5,11 @@ import (
|
|||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
"github.com/pikami/cosmium/internal/repositories"
|
|
||||||
repositorymodels "github.com/pikami/cosmium/internal/repository_models"
|
repositorymodels "github.com/pikami/cosmium/internal/repository_models"
|
||||||
)
|
)
|
||||||
|
|
||||||
func GetAllDatabases(c *gin.Context) {
|
func (h *Handlers) GetAllDatabases(c *gin.Context) {
|
||||||
databases, status := repositories.GetAllDatabases()
|
databases, status := h.repository.GetAllDatabases()
|
||||||
if status == repositorymodels.StatusOk {
|
if status == repositorymodels.StatusOk {
|
||||||
c.Header("x-ms-item-count", fmt.Sprintf("%d", len(databases)))
|
c.Header("x-ms-item-count", fmt.Sprintf("%d", len(databases)))
|
||||||
c.IndentedJSON(http.StatusOK, gin.H{
|
c.IndentedJSON(http.StatusOK, gin.H{
|
||||||
@@ -24,10 +23,10 @@ func GetAllDatabases(c *gin.Context) {
|
|||||||
c.IndentedJSON(http.StatusInternalServerError, gin.H{"message": "Unknown error"})
|
c.IndentedJSON(http.StatusInternalServerError, gin.H{"message": "Unknown error"})
|
||||||
}
|
}
|
||||||
|
|
||||||
func GetDatabase(c *gin.Context) {
|
func (h *Handlers) GetDatabase(c *gin.Context) {
|
||||||
id := c.Param("databaseId")
|
id := c.Param("databaseId")
|
||||||
|
|
||||||
database, status := repositories.GetDatabase(id)
|
database, status := h.repository.GetDatabase(id)
|
||||||
if status == repositorymodels.StatusOk {
|
if status == repositorymodels.StatusOk {
|
||||||
c.IndentedJSON(http.StatusOK, database)
|
c.IndentedJSON(http.StatusOK, database)
|
||||||
return
|
return
|
||||||
@@ -41,10 +40,10 @@ func GetDatabase(c *gin.Context) {
|
|||||||
c.IndentedJSON(http.StatusInternalServerError, gin.H{"message": "Unknown error"})
|
c.IndentedJSON(http.StatusInternalServerError, gin.H{"message": "Unknown error"})
|
||||||
}
|
}
|
||||||
|
|
||||||
func DeleteDatabase(c *gin.Context) {
|
func (h *Handlers) DeleteDatabase(c *gin.Context) {
|
||||||
id := c.Param("databaseId")
|
id := c.Param("databaseId")
|
||||||
|
|
||||||
status := repositories.DeleteDatabase(id)
|
status := h.repository.DeleteDatabase(id)
|
||||||
if status == repositorymodels.StatusOk {
|
if status == repositorymodels.StatusOk {
|
||||||
c.Status(http.StatusNoContent)
|
c.Status(http.StatusNoContent)
|
||||||
return
|
return
|
||||||
@@ -58,7 +57,7 @@ func DeleteDatabase(c *gin.Context) {
|
|||||||
c.IndentedJSON(http.StatusInternalServerError, gin.H{"message": "Unknown error"})
|
c.IndentedJSON(http.StatusInternalServerError, gin.H{"message": "Unknown error"})
|
||||||
}
|
}
|
||||||
|
|
||||||
func CreateDatabase(c *gin.Context) {
|
func (h *Handlers) CreateDatabase(c *gin.Context) {
|
||||||
var newDatabase repositorymodels.Database
|
var newDatabase repositorymodels.Database
|
||||||
|
|
||||||
if err := c.BindJSON(&newDatabase); err != nil {
|
if err := c.BindJSON(&newDatabase); err != nil {
|
||||||
@@ -71,7 +70,7 @@ func CreateDatabase(c *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
createdDatabase, status := repositories.CreateDatabase(newDatabase)
|
createdDatabase, status := h.repository.CreateDatabase(newDatabase)
|
||||||
if status == repositorymodels.Conflict {
|
if status == repositorymodels.Conflict {
|
||||||
c.IndentedJSON(http.StatusConflict, gin.H{"message": "Conflict"})
|
c.IndentedJSON(http.StatusConflict, gin.H{"message": "Conflict"})
|
||||||
return
|
return
|
||||||
|
|||||||
@@ -6,21 +6,20 @@ import (
|
|||||||
"net/http"
|
"net/http"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
|
||||||
jsonpatch "github.com/evanphx/json-patch/v5"
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
"github.com/pikami/cosmium/internal/constants"
|
"github.com/pikami/cosmium/internal/constants"
|
||||||
"github.com/pikami/cosmium/internal/logger"
|
"github.com/pikami/cosmium/internal/logger"
|
||||||
"github.com/pikami/cosmium/internal/repositories"
|
|
||||||
repositorymodels "github.com/pikami/cosmium/internal/repository_models"
|
repositorymodels "github.com/pikami/cosmium/internal/repository_models"
|
||||||
|
jsonpatch "github.com/pikami/json-patch/v5"
|
||||||
)
|
)
|
||||||
|
|
||||||
func GetAllDocuments(c *gin.Context) {
|
func (h *Handlers) GetAllDocuments(c *gin.Context) {
|
||||||
databaseId := c.Param("databaseId")
|
databaseId := c.Param("databaseId")
|
||||||
collectionId := c.Param("collId")
|
collectionId := c.Param("collId")
|
||||||
|
|
||||||
documents, status := repositories.GetAllDocuments(databaseId, collectionId)
|
documents, status := h.repository.GetAllDocuments(databaseId, collectionId)
|
||||||
if status == repositorymodels.StatusOk {
|
if status == repositorymodels.StatusOk {
|
||||||
collection, _ := repositories.GetCollection(databaseId, collectionId)
|
collection, _ := h.repository.GetCollection(databaseId, collectionId)
|
||||||
|
|
||||||
c.Header("x-ms-item-count", fmt.Sprintf("%d", len(documents)))
|
c.Header("x-ms-item-count", fmt.Sprintf("%d", len(documents)))
|
||||||
c.IndentedJSON(http.StatusOK, gin.H{
|
c.IndentedJSON(http.StatusOK, gin.H{
|
||||||
@@ -34,12 +33,12 @@ func GetAllDocuments(c *gin.Context) {
|
|||||||
c.IndentedJSON(http.StatusInternalServerError, gin.H{"message": "Unknown error"})
|
c.IndentedJSON(http.StatusInternalServerError, gin.H{"message": "Unknown error"})
|
||||||
}
|
}
|
||||||
|
|
||||||
func GetDocument(c *gin.Context) {
|
func (h *Handlers) GetDocument(c *gin.Context) {
|
||||||
databaseId := c.Param("databaseId")
|
databaseId := c.Param("databaseId")
|
||||||
collectionId := c.Param("collId")
|
collectionId := c.Param("collId")
|
||||||
documentId := c.Param("docId")
|
documentId := c.Param("docId")
|
||||||
|
|
||||||
document, status := repositories.GetDocument(databaseId, collectionId, documentId)
|
document, status := h.repository.GetDocument(databaseId, collectionId, documentId)
|
||||||
if status == repositorymodels.StatusOk {
|
if status == repositorymodels.StatusOk {
|
||||||
c.IndentedJSON(http.StatusOK, document)
|
c.IndentedJSON(http.StatusOK, document)
|
||||||
return
|
return
|
||||||
@@ -53,12 +52,12 @@ func GetDocument(c *gin.Context) {
|
|||||||
c.IndentedJSON(http.StatusInternalServerError, gin.H{"message": "Unknown error"})
|
c.IndentedJSON(http.StatusInternalServerError, gin.H{"message": "Unknown error"})
|
||||||
}
|
}
|
||||||
|
|
||||||
func DeleteDocument(c *gin.Context) {
|
func (h *Handlers) DeleteDocument(c *gin.Context) {
|
||||||
databaseId := c.Param("databaseId")
|
databaseId := c.Param("databaseId")
|
||||||
collectionId := c.Param("collId")
|
collectionId := c.Param("collId")
|
||||||
documentId := c.Param("docId")
|
documentId := c.Param("docId")
|
||||||
|
|
||||||
status := repositories.DeleteDocument(databaseId, collectionId, documentId)
|
status := h.repository.DeleteDocument(databaseId, collectionId, documentId)
|
||||||
if status == repositorymodels.StatusOk {
|
if status == repositorymodels.StatusOk {
|
||||||
c.Status(http.StatusNoContent)
|
c.Status(http.StatusNoContent)
|
||||||
return
|
return
|
||||||
@@ -73,7 +72,7 @@ func DeleteDocument(c *gin.Context) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// TODO: Maybe move "replace" logic to repository
|
// TODO: Maybe move "replace" logic to repository
|
||||||
func ReplaceDocument(c *gin.Context) {
|
func (h *Handlers) ReplaceDocument(c *gin.Context) {
|
||||||
databaseId := c.Param("databaseId")
|
databaseId := c.Param("databaseId")
|
||||||
collectionId := c.Param("collId")
|
collectionId := c.Param("collId")
|
||||||
documentId := c.Param("docId")
|
documentId := c.Param("docId")
|
||||||
@@ -84,13 +83,13 @@ func ReplaceDocument(c *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
status := repositories.DeleteDocument(databaseId, collectionId, documentId)
|
status := h.repository.DeleteDocument(databaseId, collectionId, documentId)
|
||||||
if status == repositorymodels.StatusNotFound {
|
if status == repositorymodels.StatusNotFound {
|
||||||
c.IndentedJSON(http.StatusNotFound, gin.H{"message": "NotFound"})
|
c.IndentedJSON(http.StatusNotFound, gin.H{"message": "NotFound"})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
createdDocument, status := repositories.CreateDocument(databaseId, collectionId, requestBody)
|
createdDocument, status := h.repository.CreateDocument(databaseId, collectionId, requestBody)
|
||||||
if status == repositorymodels.Conflict {
|
if status == repositorymodels.Conflict {
|
||||||
c.IndentedJSON(http.StatusConflict, gin.H{"message": "Conflict"})
|
c.IndentedJSON(http.StatusConflict, gin.H{"message": "Conflict"})
|
||||||
return
|
return
|
||||||
@@ -104,12 +103,12 @@ func ReplaceDocument(c *gin.Context) {
|
|||||||
c.IndentedJSON(http.StatusInternalServerError, gin.H{"message": "Unknown error"})
|
c.IndentedJSON(http.StatusInternalServerError, gin.H{"message": "Unknown error"})
|
||||||
}
|
}
|
||||||
|
|
||||||
func PatchDocument(c *gin.Context) {
|
func (h *Handlers) PatchDocument(c *gin.Context) {
|
||||||
databaseId := c.Param("databaseId")
|
databaseId := c.Param("databaseId")
|
||||||
collectionId := c.Param("collId")
|
collectionId := c.Param("collId")
|
||||||
documentId := c.Param("docId")
|
documentId := c.Param("docId")
|
||||||
|
|
||||||
document, status := repositories.GetDocument(databaseId, collectionId, documentId)
|
document, status := h.repository.GetDocument(databaseId, collectionId, documentId)
|
||||||
if status == repositorymodels.StatusNotFound {
|
if status == repositorymodels.StatusNotFound {
|
||||||
c.IndentedJSON(http.StatusNotFound, gin.H{"message": "NotFound"})
|
c.IndentedJSON(http.StatusNotFound, gin.H{"message": "NotFound"})
|
||||||
return
|
return
|
||||||
@@ -160,13 +159,13 @@ func PatchDocument(c *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
status = repositories.DeleteDocument(databaseId, collectionId, documentId)
|
status = h.repository.DeleteDocument(databaseId, collectionId, documentId)
|
||||||
if status == repositorymodels.StatusNotFound {
|
if status == repositorymodels.StatusNotFound {
|
||||||
c.IndentedJSON(http.StatusNotFound, gin.H{"message": "NotFound"})
|
c.IndentedJSON(http.StatusNotFound, gin.H{"message": "NotFound"})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
createdDocument, status := repositories.CreateDocument(databaseId, collectionId, modifiedDocument)
|
createdDocument, status := h.repository.CreateDocument(databaseId, collectionId, modifiedDocument)
|
||||||
if status == repositorymodels.Conflict {
|
if status == repositorymodels.Conflict {
|
||||||
c.IndentedJSON(http.StatusConflict, gin.H{"message": "Conflict"})
|
c.IndentedJSON(http.StatusConflict, gin.H{"message": "Conflict"})
|
||||||
return
|
return
|
||||||
@@ -180,7 +179,7 @@ func PatchDocument(c *gin.Context) {
|
|||||||
c.IndentedJSON(http.StatusInternalServerError, gin.H{"message": "Unknown error"})
|
c.IndentedJSON(http.StatusInternalServerError, gin.H{"message": "Unknown error"})
|
||||||
}
|
}
|
||||||
|
|
||||||
func DocumentsPost(c *gin.Context) {
|
func (h *Handlers) DocumentsPost(c *gin.Context) {
|
||||||
databaseId := c.Param("databaseId")
|
databaseId := c.Param("databaseId")
|
||||||
collectionId := c.Param("collId")
|
collectionId := c.Param("collId")
|
||||||
|
|
||||||
@@ -202,14 +201,14 @@ func DocumentsPost(c *gin.Context) {
|
|||||||
queryParameters = parametersToMap(paramsArray)
|
queryParameters = parametersToMap(paramsArray)
|
||||||
}
|
}
|
||||||
|
|
||||||
docs, status := repositories.ExecuteQueryDocuments(databaseId, collectionId, query.(string), queryParameters)
|
docs, status := h.repository.ExecuteQueryDocuments(databaseId, collectionId, query.(string), queryParameters)
|
||||||
if status != repositorymodels.StatusOk {
|
if status != repositorymodels.StatusOk {
|
||||||
// TODO: Currently we return everything if the query fails
|
// TODO: Currently we return everything if the query fails
|
||||||
GetAllDocuments(c)
|
h.GetAllDocuments(c)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
collection, _ := repositories.GetCollection(databaseId, collectionId)
|
collection, _ := h.repository.GetCollection(databaseId, collectionId)
|
||||||
c.Header("x-ms-item-count", fmt.Sprintf("%d", len(docs)))
|
c.Header("x-ms-item-count", fmt.Sprintf("%d", len(docs)))
|
||||||
c.IndentedJSON(http.StatusOK, gin.H{
|
c.IndentedJSON(http.StatusOK, gin.H{
|
||||||
"_rid": collection.ResourceID,
|
"_rid": collection.ResourceID,
|
||||||
@@ -226,10 +225,10 @@ func DocumentsPost(c *gin.Context) {
|
|||||||
|
|
||||||
isUpsert, _ := strconv.ParseBool(c.GetHeader("x-ms-documentdb-is-upsert"))
|
isUpsert, _ := strconv.ParseBool(c.GetHeader("x-ms-documentdb-is-upsert"))
|
||||||
if isUpsert {
|
if isUpsert {
|
||||||
repositories.DeleteDocument(databaseId, collectionId, requestBody["id"].(string))
|
h.repository.DeleteDocument(databaseId, collectionId, requestBody["id"].(string))
|
||||||
}
|
}
|
||||||
|
|
||||||
createdDocument, status := repositories.CreateDocument(databaseId, collectionId, requestBody)
|
createdDocument, status := h.repository.CreateDocument(databaseId, collectionId, requestBody)
|
||||||
if status == repositorymodels.Conflict {
|
if status == repositorymodels.Conflict {
|
||||||
c.IndentedJSON(http.StatusConflict, gin.H{"message": "Conflict"})
|
c.IndentedJSON(http.StatusConflict, gin.H{"message": "Conflict"})
|
||||||
return
|
return
|
||||||
|
|||||||
@@ -4,15 +4,14 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
"github.com/pikami/cosmium/api/config"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func RegisterExplorerHandlers(router *gin.Engine) {
|
func (h *Handlers) RegisterExplorerHandlers(router *gin.Engine) {
|
||||||
explorer := router.Group(config.Config.ExplorerBaseUrlLocation)
|
explorer := router.Group(h.config.ExplorerBaseUrlLocation)
|
||||||
{
|
{
|
||||||
explorer.Use(func(ctx *gin.Context) {
|
explorer.Use(func(ctx *gin.Context) {
|
||||||
if ctx.Param("filepath") == "/config.json" {
|
if ctx.Param("filepath") == "/config.json" {
|
||||||
endpoint := fmt.Sprintf("https://%s:%d", config.Config.Host, config.Config.Port)
|
endpoint := fmt.Sprintf("https://%s:%d", h.config.Host, h.config.Port)
|
||||||
ctx.JSON(200, gin.H{
|
ctx.JSON(200, gin.H{
|
||||||
"BACKEND_ENDPOINT": endpoint,
|
"BACKEND_ENDPOINT": endpoint,
|
||||||
"MONGO_BACKEND_ENDPOINT": endpoint,
|
"MONGO_BACKEND_ENDPOINT": endpoint,
|
||||||
@@ -25,8 +24,8 @@ func RegisterExplorerHandlers(router *gin.Engine) {
|
|||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
if config.Config.ExplorerPath != "" {
|
if h.config.ExplorerPath != "" {
|
||||||
explorer.Static("/", config.Config.ExplorerPath)
|
explorer.Static("/", h.config.ExplorerPath)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
18
api/handlers/handlers.go
Normal file
18
api/handlers/handlers.go
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
package handlers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/pikami/cosmium/api/config"
|
||||||
|
"github.com/pikami/cosmium/internal/repositories"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Handlers struct {
|
||||||
|
repository *repositories.DataRepository
|
||||||
|
config config.ServerConfig
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewHandlers(dataRepository *repositories.DataRepository, config config.ServerConfig) *Handlers {
|
||||||
|
return &Handlers{
|
||||||
|
repository: dataRepository,
|
||||||
|
config: config,
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -10,11 +10,11 @@ import (
|
|||||||
"github.com/pikami/cosmium/internal/logger"
|
"github.com/pikami/cosmium/internal/logger"
|
||||||
)
|
)
|
||||||
|
|
||||||
func Authentication() gin.HandlerFunc {
|
func Authentication(config config.ServerConfig) gin.HandlerFunc {
|
||||||
return func(c *gin.Context) {
|
return func(c *gin.Context) {
|
||||||
requestUrl := c.Request.URL.String()
|
requestUrl := c.Request.URL.String()
|
||||||
if config.Config.DisableAuth ||
|
if config.DisableAuth ||
|
||||||
strings.HasPrefix(requestUrl, config.Config.ExplorerBaseUrlLocation) ||
|
strings.HasPrefix(requestUrl, config.ExplorerBaseUrlLocation) ||
|
||||||
strings.HasPrefix(requestUrl, "/cosmium") {
|
strings.HasPrefix(requestUrl, "/cosmium") {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -25,7 +25,7 @@ func Authentication() gin.HandlerFunc {
|
|||||||
authHeader := c.Request.Header.Get("authorization")
|
authHeader := c.Request.Header.Get("authorization")
|
||||||
date := c.Request.Header.Get("x-ms-date")
|
date := c.Request.Header.Get("x-ms-date")
|
||||||
expectedSignature := authentication.GenerateSignature(
|
expectedSignature := authentication.GenerateSignature(
|
||||||
c.Request.Method, resourceType, resourceId, date, config.Config.AccountKey)
|
c.Request.Method, resourceType, resourceId, date, config.AccountKey)
|
||||||
|
|
||||||
decoded, _ := url.QueryUnescape(authHeader)
|
decoded, _ := url.QueryUnescape(authHeader)
|
||||||
params, _ := url.ParseQuery(decoded)
|
params, _ := url.ParseQuery(decoded)
|
||||||
|
|||||||
@@ -7,10 +7,10 @@ import (
|
|||||||
"github.com/pikami/cosmium/api/config"
|
"github.com/pikami/cosmium/api/config"
|
||||||
)
|
)
|
||||||
|
|
||||||
func StripTrailingSlashes(r *gin.Engine) gin.HandlerFunc {
|
func StripTrailingSlashes(r *gin.Engine, config config.ServerConfig) gin.HandlerFunc {
|
||||||
return func(c *gin.Context) {
|
return func(c *gin.Context) {
|
||||||
path := c.Request.URL.Path
|
path := c.Request.URL.Path
|
||||||
if len(path) > 1 && path[len(path)-1] == '/' && !strings.Contains(path, config.Config.ExplorerBaseUrlLocation) {
|
if len(path) > 1 && path[len(path)-1] == '/' && !strings.Contains(path, config.ExplorerBaseUrlLocation) {
|
||||||
c.Request.URL.Path = path[:len(path)-1]
|
c.Request.URL.Path = path[:len(path)-1]
|
||||||
r.HandleContext(c)
|
r.HandleContext(c)
|
||||||
c.Abort()
|
c.Abort()
|
||||||
|
|||||||
@@ -5,11 +5,10 @@ import (
|
|||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
"github.com/pikami/cosmium/internal/repositories"
|
|
||||||
repositorymodels "github.com/pikami/cosmium/internal/repository_models"
|
repositorymodels "github.com/pikami/cosmium/internal/repository_models"
|
||||||
)
|
)
|
||||||
|
|
||||||
func GetPartitionKeyRanges(c *gin.Context) {
|
func (h *Handlers) GetPartitionKeyRanges(c *gin.Context) {
|
||||||
databaseId := c.Param("databaseId")
|
databaseId := c.Param("databaseId")
|
||||||
collectionId := c.Param("collId")
|
collectionId := c.Param("collId")
|
||||||
|
|
||||||
@@ -18,7 +17,7 @@ func GetPartitionKeyRanges(c *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
partitionKeyRanges, status := repositories.GetPartitionKeyRanges(databaseId, collectionId)
|
partitionKeyRanges, status := h.repository.GetPartitionKeyRanges(databaseId, collectionId)
|
||||||
if status == repositorymodels.StatusOk {
|
if status == repositorymodels.StatusOk {
|
||||||
c.Header("etag", "\"420\"")
|
c.Header("etag", "\"420\"")
|
||||||
c.Header("lsn", "420")
|
c.Header("lsn", "420")
|
||||||
@@ -27,7 +26,7 @@ func GetPartitionKeyRanges(c *gin.Context) {
|
|||||||
c.Header("x-ms-item-count", fmt.Sprintf("%d", len(partitionKeyRanges)))
|
c.Header("x-ms-item-count", fmt.Sprintf("%d", len(partitionKeyRanges)))
|
||||||
|
|
||||||
collectionRid := collectionId
|
collectionRid := collectionId
|
||||||
collection, _ := repositories.GetCollection(databaseId, collectionId)
|
collection, _ := h.repository.GetCollection(databaseId, collectionId)
|
||||||
if collection.ResourceID != "" {
|
if collection.ResourceID != "" {
|
||||||
collectionRid = collection.ResourceID
|
collectionRid = collection.ResourceID
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,27 +5,26 @@ import (
|
|||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
"github.com/pikami/cosmium/api/config"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func GetServerInfo(c *gin.Context) {
|
func (h *Handlers) GetServerInfo(c *gin.Context) {
|
||||||
c.IndentedJSON(http.StatusOK, gin.H{
|
c.IndentedJSON(http.StatusOK, gin.H{
|
||||||
"_self": "",
|
"_self": "",
|
||||||
"id": config.Config.DatabaseAccount,
|
"id": h.config.DatabaseAccount,
|
||||||
"_rid": fmt.Sprintf("%s.%s", config.Config.DatabaseAccount, config.Config.DatabaseDomain),
|
"_rid": fmt.Sprintf("%s.%s", h.config.DatabaseAccount, h.config.DatabaseDomain),
|
||||||
"media": "//media/",
|
"media": "//media/",
|
||||||
"addresses": "//addresses/",
|
"addresses": "//addresses/",
|
||||||
"_dbs": "//dbs/",
|
"_dbs": "//dbs/",
|
||||||
"writableLocations": []map[string]interface{}{
|
"writableLocations": []map[string]interface{}{
|
||||||
{
|
{
|
||||||
"name": "South Central US",
|
"name": "South Central US",
|
||||||
"databaseAccountEndpoint": config.Config.DatabaseEndpoint,
|
"databaseAccountEndpoint": h.config.DatabaseEndpoint,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
"readableLocations": []map[string]interface{}{
|
"readableLocations": []map[string]interface{}{
|
||||||
{
|
{
|
||||||
"name": "South Central US",
|
"name": "South Central US",
|
||||||
"databaseAccountEndpoint": config.Config.DatabaseEndpoint,
|
"databaseAccountEndpoint": h.config.DatabaseEndpoint,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
"enableMultipleWriteLocations": false,
|
"enableMultipleWriteLocations": false,
|
||||||
|
|||||||
@@ -5,15 +5,14 @@ import (
|
|||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
"github.com/pikami/cosmium/internal/repositories"
|
|
||||||
repositorymodels "github.com/pikami/cosmium/internal/repository_models"
|
repositorymodels "github.com/pikami/cosmium/internal/repository_models"
|
||||||
)
|
)
|
||||||
|
|
||||||
func GetAllStoredProcedures(c *gin.Context) {
|
func (h *Handlers) GetAllStoredProcedures(c *gin.Context) {
|
||||||
databaseId := c.Param("databaseId")
|
databaseId := c.Param("databaseId")
|
||||||
collectionId := c.Param("collId")
|
collectionId := c.Param("collId")
|
||||||
|
|
||||||
sps, status := repositories.GetAllStoredProcedures(databaseId, collectionId)
|
sps, status := h.repository.GetAllStoredProcedures(databaseId, collectionId)
|
||||||
|
|
||||||
if status == repositorymodels.StatusOk {
|
if status == repositorymodels.StatusOk {
|
||||||
c.Header("x-ms-item-count", fmt.Sprintf("%d", len(sps)))
|
c.Header("x-ms-item-count", fmt.Sprintf("%d", len(sps)))
|
||||||
|
|||||||
@@ -5,15 +5,14 @@ import (
|
|||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
"github.com/pikami/cosmium/internal/repositories"
|
|
||||||
repositorymodels "github.com/pikami/cosmium/internal/repository_models"
|
repositorymodels "github.com/pikami/cosmium/internal/repository_models"
|
||||||
)
|
)
|
||||||
|
|
||||||
func GetAllTriggers(c *gin.Context) {
|
func (h *Handlers) GetAllTriggers(c *gin.Context) {
|
||||||
databaseId := c.Param("databaseId")
|
databaseId := c.Param("databaseId")
|
||||||
collectionId := c.Param("collId")
|
collectionId := c.Param("collId")
|
||||||
|
|
||||||
triggers, status := repositories.GetAllTriggers(databaseId, collectionId)
|
triggers, status := h.repository.GetAllTriggers(databaseId, collectionId)
|
||||||
|
|
||||||
if status == repositorymodels.StatusOk {
|
if status == repositorymodels.StatusOk {
|
||||||
c.Header("x-ms-item-count", fmt.Sprintf("%d", len(triggers)))
|
c.Header("x-ms-item-count", fmt.Sprintf("%d", len(triggers)))
|
||||||
|
|||||||
@@ -5,15 +5,14 @@ import (
|
|||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
"github.com/pikami/cosmium/internal/repositories"
|
|
||||||
repositorymodels "github.com/pikami/cosmium/internal/repository_models"
|
repositorymodels "github.com/pikami/cosmium/internal/repository_models"
|
||||||
)
|
)
|
||||||
|
|
||||||
func GetAllUserDefinedFunctions(c *gin.Context) {
|
func (h *Handlers) GetAllUserDefinedFunctions(c *gin.Context) {
|
||||||
databaseId := c.Param("databaseId")
|
databaseId := c.Param("databaseId")
|
||||||
collectionId := c.Param("collId")
|
collectionId := c.Param("collId")
|
||||||
|
|
||||||
udfs, status := repositories.GetAllUserDefinedFunctions(databaseId, collectionId)
|
udfs, status := h.repository.GetAllUserDefinedFunctions(databaseId, collectionId)
|
||||||
|
|
||||||
if status == repositorymodels.StatusOk {
|
if status == repositorymodels.StatusOk {
|
||||||
c.Header("x-ms-item-count", fmt.Sprintf("%d", len(udfs)))
|
c.Header("x-ms-item-count", fmt.Sprintf("%d", len(udfs)))
|
||||||
|
|||||||
136
api/router.go
136
api/router.go
@@ -1,98 +1,114 @@
|
|||||||
package api
|
package api
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
"fmt"
|
"fmt"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
"github.com/pikami/cosmium/api/config"
|
|
||||||
"github.com/pikami/cosmium/api/handlers"
|
"github.com/pikami/cosmium/api/handlers"
|
||||||
"github.com/pikami/cosmium/api/handlers/middleware"
|
"github.com/pikami/cosmium/api/handlers/middleware"
|
||||||
"github.com/pikami/cosmium/internal/logger"
|
"github.com/pikami/cosmium/internal/logger"
|
||||||
|
"github.com/pikami/cosmium/internal/repositories"
|
||||||
tlsprovider "github.com/pikami/cosmium/internal/tls_provider"
|
tlsprovider "github.com/pikami/cosmium/internal/tls_provider"
|
||||||
)
|
)
|
||||||
|
|
||||||
func CreateRouter() *gin.Engine {
|
func (s *ApiServer) CreateRouter(repository *repositories.DataRepository) {
|
||||||
|
routeHandlers := handlers.NewHandlers(repository, s.config)
|
||||||
|
|
||||||
|
if !s.config.Debug {
|
||||||
|
gin.SetMode(gin.ReleaseMode)
|
||||||
|
}
|
||||||
|
|
||||||
router := gin.Default(func(e *gin.Engine) {
|
router := gin.Default(func(e *gin.Engine) {
|
||||||
e.RedirectTrailingSlash = false
|
e.RedirectTrailingSlash = false
|
||||||
})
|
})
|
||||||
|
|
||||||
if config.Config.Debug {
|
if s.config.Debug {
|
||||||
router.Use(middleware.RequestLogger())
|
router.Use(middleware.RequestLogger())
|
||||||
}
|
}
|
||||||
|
|
||||||
router.Use(middleware.StripTrailingSlashes(router))
|
router.Use(middleware.StripTrailingSlashes(router, s.config))
|
||||||
router.Use(middleware.Authentication())
|
router.Use(middleware.Authentication(s.config))
|
||||||
|
|
||||||
router.GET("/dbs/:databaseId/colls/:collId/pkranges", handlers.GetPartitionKeyRanges)
|
router.GET("/dbs/:databaseId/colls/:collId/pkranges", routeHandlers.GetPartitionKeyRanges)
|
||||||
|
|
||||||
router.POST("/dbs/:databaseId/colls/:collId/docs", handlers.DocumentsPost)
|
router.POST("/dbs/:databaseId/colls/:collId/docs", routeHandlers.DocumentsPost)
|
||||||
router.GET("/dbs/:databaseId/colls/:collId/docs", handlers.GetAllDocuments)
|
router.GET("/dbs/:databaseId/colls/:collId/docs", routeHandlers.GetAllDocuments)
|
||||||
router.GET("/dbs/:databaseId/colls/:collId/docs/:docId", handlers.GetDocument)
|
router.GET("/dbs/:databaseId/colls/:collId/docs/:docId", routeHandlers.GetDocument)
|
||||||
router.PUT("/dbs/:databaseId/colls/:collId/docs/:docId", handlers.ReplaceDocument)
|
router.PUT("/dbs/:databaseId/colls/:collId/docs/:docId", routeHandlers.ReplaceDocument)
|
||||||
router.PATCH("/dbs/:databaseId/colls/:collId/docs/:docId", handlers.PatchDocument)
|
router.PATCH("/dbs/:databaseId/colls/:collId/docs/:docId", routeHandlers.PatchDocument)
|
||||||
router.DELETE("/dbs/:databaseId/colls/:collId/docs/:docId", handlers.DeleteDocument)
|
router.DELETE("/dbs/:databaseId/colls/:collId/docs/:docId", routeHandlers.DeleteDocument)
|
||||||
|
|
||||||
router.POST("/dbs/:databaseId/colls", handlers.CreateCollection)
|
router.POST("/dbs/:databaseId/colls", routeHandlers.CreateCollection)
|
||||||
router.GET("/dbs/:databaseId/colls", handlers.GetAllCollections)
|
router.GET("/dbs/:databaseId/colls", routeHandlers.GetAllCollections)
|
||||||
router.GET("/dbs/:databaseId/colls/:collId", handlers.GetCollection)
|
router.GET("/dbs/:databaseId/colls/:collId", routeHandlers.GetCollection)
|
||||||
router.DELETE("/dbs/:databaseId/colls/:collId", handlers.DeleteCollection)
|
router.DELETE("/dbs/:databaseId/colls/:collId", routeHandlers.DeleteCollection)
|
||||||
|
|
||||||
router.POST("/dbs", handlers.CreateDatabase)
|
router.POST("/dbs", routeHandlers.CreateDatabase)
|
||||||
router.GET("/dbs", handlers.GetAllDatabases)
|
router.GET("/dbs", routeHandlers.GetAllDatabases)
|
||||||
router.GET("/dbs/:databaseId", handlers.GetDatabase)
|
router.GET("/dbs/:databaseId", routeHandlers.GetDatabase)
|
||||||
router.DELETE("/dbs/:databaseId", handlers.DeleteDatabase)
|
router.DELETE("/dbs/:databaseId", routeHandlers.DeleteDatabase)
|
||||||
|
|
||||||
router.GET("/dbs/:databaseId/colls/:collId/udfs", handlers.GetAllUserDefinedFunctions)
|
router.GET("/dbs/:databaseId/colls/:collId/udfs", routeHandlers.GetAllUserDefinedFunctions)
|
||||||
router.GET("/dbs/:databaseId/colls/:collId/sprocs", handlers.GetAllStoredProcedures)
|
router.GET("/dbs/:databaseId/colls/:collId/sprocs", routeHandlers.GetAllStoredProcedures)
|
||||||
router.GET("/dbs/:databaseId/colls/:collId/triggers", handlers.GetAllTriggers)
|
router.GET("/dbs/:databaseId/colls/:collId/triggers", routeHandlers.GetAllTriggers)
|
||||||
|
|
||||||
router.GET("/offers", handlers.GetOffers)
|
router.GET("/offers", handlers.GetOffers)
|
||||||
router.GET("/", handlers.GetServerInfo)
|
router.GET("/", routeHandlers.GetServerInfo)
|
||||||
|
|
||||||
router.GET("/cosmium/export", handlers.CosmiumExport)
|
router.GET("/cosmium/export", routeHandlers.CosmiumExport)
|
||||||
|
|
||||||
handlers.RegisterExplorerHandlers(router)
|
routeHandlers.RegisterExplorerHandlers(router)
|
||||||
|
|
||||||
return router
|
s.router = router
|
||||||
}
|
}
|
||||||
|
|
||||||
func StartAPI() {
|
func (s *ApiServer) Start() {
|
||||||
if !config.Config.Debug {
|
listenAddress := fmt.Sprintf(":%d", s.config.Port)
|
||||||
gin.SetMode(gin.ReleaseMode)
|
s.isActive = true
|
||||||
}
|
|
||||||
|
|
||||||
router := CreateRouter()
|
|
||||||
listenAddress := fmt.Sprintf(":%d", config.Config.Port)
|
|
||||||
|
|
||||||
if config.Config.TLS_CertificatePath != "" && config.Config.TLS_CertificateKey != "" {
|
|
||||||
err := router.RunTLS(
|
|
||||||
listenAddress,
|
|
||||||
config.Config.TLS_CertificatePath,
|
|
||||||
config.Config.TLS_CertificateKey)
|
|
||||||
if err != nil {
|
|
||||||
logger.Error("Failed to start HTTPS server:", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if config.Config.DisableTls {
|
|
||||||
router.Run(listenAddress)
|
|
||||||
}
|
|
||||||
|
|
||||||
tlsConfig := tlsprovider.GetDefaultTlsConfig()
|
|
||||||
server := &http.Server{
|
server := &http.Server{
|
||||||
Addr: listenAddress,
|
Addr: listenAddress,
|
||||||
Handler: router.Handler(),
|
Handler: s.router.Handler(),
|
||||||
TLSConfig: tlsConfig,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
logger.Infof("Listening and serving HTTPS on %s\n", server.Addr)
|
go func() {
|
||||||
err := server.ListenAndServeTLS("", "")
|
<-s.stopServer
|
||||||
if err != nil {
|
logger.Info("Shutting down server...")
|
||||||
logger.Error("Failed to start HTTPS server:", err)
|
err := server.Shutdown(context.TODO())
|
||||||
}
|
if err != nil {
|
||||||
|
logger.Error("Failed to shutdown server:", err)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
router.Run()
|
go func() {
|
||||||
|
if s.config.DisableTls {
|
||||||
|
logger.Infof("Listening and serving HTTP on %s\n", server.Addr)
|
||||||
|
err := server.ListenAndServe()
|
||||||
|
if err != nil {
|
||||||
|
logger.Error("Failed to start HTTP server:", err)
|
||||||
|
}
|
||||||
|
s.isActive = false
|
||||||
|
} else if s.config.TLS_CertificatePath != "" && s.config.TLS_CertificateKey != "" {
|
||||||
|
logger.Infof("Listening and serving HTTPS on %s\n", server.Addr)
|
||||||
|
err := server.ListenAndServeTLS(
|
||||||
|
s.config.TLS_CertificatePath,
|
||||||
|
s.config.TLS_CertificateKey)
|
||||||
|
if err != nil {
|
||||||
|
logger.Error("Failed to start HTTPS server:", err)
|
||||||
|
}
|
||||||
|
s.isActive = false
|
||||||
|
} else {
|
||||||
|
tlsConfig := tlsprovider.GetDefaultTlsConfig()
|
||||||
|
server.TLSConfig = tlsConfig
|
||||||
|
|
||||||
|
logger.Infof("Listening and serving HTTPS on %s\n", server.Addr)
|
||||||
|
err := server.ListenAndServeTLS("", "")
|
||||||
|
if err != nil {
|
||||||
|
logger.Error("Failed to start HTTPS server:", err)
|
||||||
|
}
|
||||||
|
s.isActive = false
|
||||||
|
}
|
||||||
|
}()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,16 +11,15 @@ import (
|
|||||||
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
|
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
|
||||||
"github.com/Azure/azure-sdk-for-go/sdk/data/azcosmos"
|
"github.com/Azure/azure-sdk-for-go/sdk/data/azcosmos"
|
||||||
"github.com/pikami/cosmium/api/config"
|
"github.com/pikami/cosmium/api/config"
|
||||||
"github.com/pikami/cosmium/internal/repositories"
|
|
||||||
"github.com/stretchr/testify/assert"
|
"github.com/stretchr/testify/assert"
|
||||||
)
|
)
|
||||||
|
|
||||||
func Test_Authentication(t *testing.T) {
|
func Test_Authentication(t *testing.T) {
|
||||||
ts := runTestServer()
|
ts := runTestServer()
|
||||||
defer ts.Close()
|
defer ts.Server.Close()
|
||||||
|
|
||||||
t.Run("Should get 200 when correct account key is used", func(t *testing.T) {
|
t.Run("Should get 200 when correct account key is used", func(t *testing.T) {
|
||||||
repositories.DeleteDatabase(testDatabaseName)
|
ts.Repository.DeleteDatabase(testDatabaseName)
|
||||||
client, err := azcosmos.NewClientFromConnectionString(
|
client, err := azcosmos.NewClientFromConnectionString(
|
||||||
fmt.Sprintf("AccountEndpoint=%s;AccountKey=%s", ts.URL, config.DefaultAccountKey),
|
fmt.Sprintf("AccountEndpoint=%s;AccountKey=%s", ts.URL, config.DefaultAccountKey),
|
||||||
&azcosmos.ClientOptions{},
|
&azcosmos.ClientOptions{},
|
||||||
@@ -35,26 +34,8 @@ func Test_Authentication(t *testing.T) {
|
|||||||
assert.Equal(t, createResponse.DatabaseProperties.ID, testDatabaseName)
|
assert.Equal(t, createResponse.DatabaseProperties.ID, testDatabaseName)
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("Should get 200 when wrong account key is used, but authentication is dissabled", func(t *testing.T) {
|
|
||||||
config.Config.DisableAuth = true
|
|
||||||
repositories.DeleteDatabase(testDatabaseName)
|
|
||||||
client, err := azcosmos.NewClientFromConnectionString(
|
|
||||||
fmt.Sprintf("AccountEndpoint=%s;AccountKey=%s", ts.URL, "AAAA"),
|
|
||||||
&azcosmos.ClientOptions{},
|
|
||||||
)
|
|
||||||
assert.Nil(t, err)
|
|
||||||
|
|
||||||
createResponse, err := client.CreateDatabase(
|
|
||||||
context.TODO(),
|
|
||||||
azcosmos.DatabaseProperties{ID: testDatabaseName},
|
|
||||||
&azcosmos.CreateDatabaseOptions{})
|
|
||||||
assert.Nil(t, err)
|
|
||||||
assert.Equal(t, createResponse.DatabaseProperties.ID, testDatabaseName)
|
|
||||||
config.Config.DisableAuth = false
|
|
||||||
})
|
|
||||||
|
|
||||||
t.Run("Should get 401 when wrong account key is used", func(t *testing.T) {
|
t.Run("Should get 401 when wrong account key is used", func(t *testing.T) {
|
||||||
repositories.DeleteDatabase(testDatabaseName)
|
ts.Repository.DeleteDatabase(testDatabaseName)
|
||||||
client, err := azcosmos.NewClientFromConnectionString(
|
client, err := azcosmos.NewClientFromConnectionString(
|
||||||
fmt.Sprintf("AccountEndpoint=%s;AccountKey=%s", ts.URL, "AAAA"),
|
fmt.Sprintf("AccountEndpoint=%s;AccountKey=%s", ts.URL, "AAAA"),
|
||||||
&azcosmos.ClientOptions{},
|
&azcosmos.ClientOptions{},
|
||||||
@@ -85,3 +66,29 @@ func Test_Authentication(t *testing.T) {
|
|||||||
assert.Contains(t, string(responseBody), "BACKEND_ENDPOINT")
|
assert.Contains(t, string(responseBody), "BACKEND_ENDPOINT")
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func Test_Authentication_Disabled(t *testing.T) {
|
||||||
|
ts := runTestServerCustomConfig(config.ServerConfig{
|
||||||
|
AccountKey: config.DefaultAccountKey,
|
||||||
|
ExplorerPath: "/tmp/nothing",
|
||||||
|
ExplorerBaseUrlLocation: config.ExplorerBaseUrlLocation,
|
||||||
|
DisableAuth: true,
|
||||||
|
})
|
||||||
|
defer ts.Server.Close()
|
||||||
|
|
||||||
|
t.Run("Should get 200 when wrong account key is used, but authentication is dissabled", func(t *testing.T) {
|
||||||
|
ts.Repository.DeleteDatabase(testDatabaseName)
|
||||||
|
client, err := azcosmos.NewClientFromConnectionString(
|
||||||
|
fmt.Sprintf("AccountEndpoint=%s;AccountKey=%s", ts.URL, "AAAA"),
|
||||||
|
&azcosmos.ClientOptions{},
|
||||||
|
)
|
||||||
|
assert.Nil(t, err)
|
||||||
|
|
||||||
|
createResponse, err := client.CreateDatabase(
|
||||||
|
context.TODO(),
|
||||||
|
azcosmos.DatabaseProperties{ID: testDatabaseName},
|
||||||
|
&azcosmos.CreateDatabaseOptions{})
|
||||||
|
assert.Nil(t, err)
|
||||||
|
assert.Equal(t, createResponse.DatabaseProperties.ID, testDatabaseName)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|||||||
@@ -10,22 +10,21 @@ import (
|
|||||||
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
|
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
|
||||||
"github.com/Azure/azure-sdk-for-go/sdk/data/azcosmos"
|
"github.com/Azure/azure-sdk-for-go/sdk/data/azcosmos"
|
||||||
"github.com/pikami/cosmium/api/config"
|
"github.com/pikami/cosmium/api/config"
|
||||||
"github.com/pikami/cosmium/internal/repositories"
|
|
||||||
repositorymodels "github.com/pikami/cosmium/internal/repository_models"
|
repositorymodels "github.com/pikami/cosmium/internal/repository_models"
|
||||||
"github.com/stretchr/testify/assert"
|
"github.com/stretchr/testify/assert"
|
||||||
)
|
)
|
||||||
|
|
||||||
func Test_Collections(t *testing.T) {
|
func Test_Collections(t *testing.T) {
|
||||||
ts := runTestServer()
|
ts := runTestServer()
|
||||||
defer ts.Close()
|
defer ts.Server.Close()
|
||||||
|
|
||||||
client, err := azcosmos.NewClientFromConnectionString(
|
client, err := azcosmos.NewClientFromConnectionString(
|
||||||
fmt.Sprintf("AccountEndpoint=%s;AccountKey=%s", ts.URL, config.Config.AccountKey),
|
fmt.Sprintf("AccountEndpoint=%s;AccountKey=%s", ts.URL, config.DefaultAccountKey),
|
||||||
&azcosmos.ClientOptions{},
|
&azcosmos.ClientOptions{},
|
||||||
)
|
)
|
||||||
assert.Nil(t, err)
|
assert.Nil(t, err)
|
||||||
|
|
||||||
repositories.CreateDatabase(repositorymodels.Database{ID: testDatabaseName})
|
ts.Repository.CreateDatabase(repositorymodels.Database{ID: testDatabaseName})
|
||||||
databaseClient, err := client.NewDatabase(testDatabaseName)
|
databaseClient, err := client.NewDatabase(testDatabaseName)
|
||||||
assert.Nil(t, err)
|
assert.Nil(t, err)
|
||||||
|
|
||||||
@@ -40,7 +39,7 @@ func Test_Collections(t *testing.T) {
|
|||||||
})
|
})
|
||||||
|
|
||||||
t.Run("Should return conflict when collection exists", func(t *testing.T) {
|
t.Run("Should return conflict when collection exists", func(t *testing.T) {
|
||||||
repositories.CreateCollection(testDatabaseName, repositorymodels.Collection{
|
ts.Repository.CreateCollection(testDatabaseName, repositorymodels.Collection{
|
||||||
ID: testCollectionName,
|
ID: testCollectionName,
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -60,7 +59,7 @@ func Test_Collections(t *testing.T) {
|
|||||||
|
|
||||||
t.Run("Collection Read", func(t *testing.T) {
|
t.Run("Collection Read", func(t *testing.T) {
|
||||||
t.Run("Should read collection", func(t *testing.T) {
|
t.Run("Should read collection", func(t *testing.T) {
|
||||||
repositories.CreateCollection(testDatabaseName, repositorymodels.Collection{
|
ts.Repository.CreateCollection(testDatabaseName, repositorymodels.Collection{
|
||||||
ID: testCollectionName,
|
ID: testCollectionName,
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -74,7 +73,7 @@ func Test_Collections(t *testing.T) {
|
|||||||
})
|
})
|
||||||
|
|
||||||
t.Run("Should return not found when collection does not exist", func(t *testing.T) {
|
t.Run("Should return not found when collection does not exist", func(t *testing.T) {
|
||||||
repositories.DeleteCollection(testDatabaseName, testCollectionName)
|
ts.Repository.DeleteCollection(testDatabaseName, testCollectionName)
|
||||||
|
|
||||||
collectionResponse, err := databaseClient.NewContainer(testCollectionName)
|
collectionResponse, err := databaseClient.NewContainer(testCollectionName)
|
||||||
assert.Nil(t, err)
|
assert.Nil(t, err)
|
||||||
@@ -93,7 +92,7 @@ func Test_Collections(t *testing.T) {
|
|||||||
|
|
||||||
t.Run("Collection Delete", func(t *testing.T) {
|
t.Run("Collection Delete", func(t *testing.T) {
|
||||||
t.Run("Should delete collection", func(t *testing.T) {
|
t.Run("Should delete collection", func(t *testing.T) {
|
||||||
repositories.CreateCollection(testDatabaseName, repositorymodels.Collection{
|
ts.Repository.CreateCollection(testDatabaseName, repositorymodels.Collection{
|
||||||
ID: testCollectionName,
|
ID: testCollectionName,
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -106,7 +105,7 @@ func Test_Collections(t *testing.T) {
|
|||||||
})
|
})
|
||||||
|
|
||||||
t.Run("Should return not found when collection does not exist", func(t *testing.T) {
|
t.Run("Should return not found when collection does not exist", func(t *testing.T) {
|
||||||
repositories.DeleteCollection(testDatabaseName, testCollectionName)
|
ts.Repository.DeleteCollection(testDatabaseName, testCollectionName)
|
||||||
|
|
||||||
collectionResponse, err := databaseClient.NewContainer(testCollectionName)
|
collectionResponse, err := databaseClient.NewContainer(testCollectionName)
|
||||||
assert.Nil(t, err)
|
assert.Nil(t, err)
|
||||||
|
|||||||
@@ -5,14 +5,37 @@ import (
|
|||||||
|
|
||||||
"github.com/pikami/cosmium/api"
|
"github.com/pikami/cosmium/api"
|
||||||
"github.com/pikami/cosmium/api/config"
|
"github.com/pikami/cosmium/api/config"
|
||||||
|
"github.com/pikami/cosmium/internal/repositories"
|
||||||
)
|
)
|
||||||
|
|
||||||
func runTestServer() *httptest.Server {
|
type TestServer struct {
|
||||||
config.Config.AccountKey = config.DefaultAccountKey
|
Server *httptest.Server
|
||||||
config.Config.ExplorerPath = "/tmp/nothing"
|
Repository *repositories.DataRepository
|
||||||
config.Config.ExplorerBaseUrlLocation = config.ExplorerBaseUrlLocation
|
URL string
|
||||||
|
}
|
||||||
|
|
||||||
return httptest.NewServer(api.CreateRouter())
|
func runTestServerCustomConfig(config config.ServerConfig) *TestServer {
|
||||||
|
repository := repositories.NewDataRepository(repositories.RepositoryOptions{})
|
||||||
|
|
||||||
|
api := api.NewApiServer(repository, config)
|
||||||
|
|
||||||
|
server := httptest.NewServer(api.GetRouter())
|
||||||
|
|
||||||
|
return &TestServer{
|
||||||
|
Server: server,
|
||||||
|
Repository: repository,
|
||||||
|
URL: server.URL,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func runTestServer() *TestServer {
|
||||||
|
config := config.ServerConfig{
|
||||||
|
AccountKey: config.DefaultAccountKey,
|
||||||
|
ExplorerPath: "/tmp/nothing",
|
||||||
|
ExplorerBaseUrlLocation: config.ExplorerBaseUrlLocation,
|
||||||
|
}
|
||||||
|
|
||||||
|
return runTestServerCustomConfig(config)
|
||||||
}
|
}
|
||||||
|
|
||||||
const (
|
const (
|
||||||
|
|||||||
@@ -10,24 +10,23 @@ import (
|
|||||||
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
|
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
|
||||||
"github.com/Azure/azure-sdk-for-go/sdk/data/azcosmos"
|
"github.com/Azure/azure-sdk-for-go/sdk/data/azcosmos"
|
||||||
"github.com/pikami/cosmium/api/config"
|
"github.com/pikami/cosmium/api/config"
|
||||||
"github.com/pikami/cosmium/internal/repositories"
|
|
||||||
repositorymodels "github.com/pikami/cosmium/internal/repository_models"
|
repositorymodels "github.com/pikami/cosmium/internal/repository_models"
|
||||||
"github.com/stretchr/testify/assert"
|
"github.com/stretchr/testify/assert"
|
||||||
)
|
)
|
||||||
|
|
||||||
func Test_Databases(t *testing.T) {
|
func Test_Databases(t *testing.T) {
|
||||||
ts := runTestServer()
|
ts := runTestServer()
|
||||||
defer ts.Close()
|
defer ts.Server.Close()
|
||||||
|
|
||||||
client, err := azcosmos.NewClientFromConnectionString(
|
client, err := azcosmos.NewClientFromConnectionString(
|
||||||
fmt.Sprintf("AccountEndpoint=%s;AccountKey=%s", ts.URL, config.Config.AccountKey),
|
fmt.Sprintf("AccountEndpoint=%s;AccountKey=%s", ts.URL, config.DefaultAccountKey),
|
||||||
&azcosmos.ClientOptions{},
|
&azcosmos.ClientOptions{},
|
||||||
)
|
)
|
||||||
assert.Nil(t, err)
|
assert.Nil(t, err)
|
||||||
|
|
||||||
t.Run("Database Create", func(t *testing.T) {
|
t.Run("Database Create", func(t *testing.T) {
|
||||||
t.Run("Should create database", func(t *testing.T) {
|
t.Run("Should create database", func(t *testing.T) {
|
||||||
repositories.DeleteDatabase(testDatabaseName)
|
ts.Repository.DeleteDatabase(testDatabaseName)
|
||||||
|
|
||||||
createResponse, err := client.CreateDatabase(context.TODO(), azcosmos.DatabaseProperties{
|
createResponse, err := client.CreateDatabase(context.TODO(), azcosmos.DatabaseProperties{
|
||||||
ID: testDatabaseName,
|
ID: testDatabaseName,
|
||||||
@@ -38,7 +37,7 @@ func Test_Databases(t *testing.T) {
|
|||||||
})
|
})
|
||||||
|
|
||||||
t.Run("Should return conflict when database exists", func(t *testing.T) {
|
t.Run("Should return conflict when database exists", func(t *testing.T) {
|
||||||
repositories.CreateDatabase(repositorymodels.Database{
|
ts.Repository.CreateDatabase(repositorymodels.Database{
|
||||||
ID: testDatabaseName,
|
ID: testDatabaseName,
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -58,7 +57,7 @@ func Test_Databases(t *testing.T) {
|
|||||||
|
|
||||||
t.Run("Database Read", func(t *testing.T) {
|
t.Run("Database Read", func(t *testing.T) {
|
||||||
t.Run("Should read database", func(t *testing.T) {
|
t.Run("Should read database", func(t *testing.T) {
|
||||||
repositories.CreateDatabase(repositorymodels.Database{
|
ts.Repository.CreateDatabase(repositorymodels.Database{
|
||||||
ID: testDatabaseName,
|
ID: testDatabaseName,
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -72,7 +71,7 @@ func Test_Databases(t *testing.T) {
|
|||||||
})
|
})
|
||||||
|
|
||||||
t.Run("Should return not found when database does not exist", func(t *testing.T) {
|
t.Run("Should return not found when database does not exist", func(t *testing.T) {
|
||||||
repositories.DeleteDatabase(testDatabaseName)
|
ts.Repository.DeleteDatabase(testDatabaseName)
|
||||||
|
|
||||||
databaseResponse, err := client.NewDatabase(testDatabaseName)
|
databaseResponse, err := client.NewDatabase(testDatabaseName)
|
||||||
assert.Nil(t, err)
|
assert.Nil(t, err)
|
||||||
@@ -91,7 +90,7 @@ func Test_Databases(t *testing.T) {
|
|||||||
|
|
||||||
t.Run("Database Delete", func(t *testing.T) {
|
t.Run("Database Delete", func(t *testing.T) {
|
||||||
t.Run("Should delete database", func(t *testing.T) {
|
t.Run("Should delete database", func(t *testing.T) {
|
||||||
repositories.CreateDatabase(repositorymodels.Database{
|
ts.Repository.CreateDatabase(repositorymodels.Database{
|
||||||
ID: testDatabaseName,
|
ID: testDatabaseName,
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -104,7 +103,7 @@ func Test_Databases(t *testing.T) {
|
|||||||
})
|
})
|
||||||
|
|
||||||
t.Run("Should return not found when database does not exist", func(t *testing.T) {
|
t.Run("Should return not found when database does not exist", func(t *testing.T) {
|
||||||
repositories.DeleteDatabase(testDatabaseName)
|
ts.Repository.DeleteDatabase(testDatabaseName)
|
||||||
|
|
||||||
databaseResponse, err := client.NewDatabase(testDatabaseName)
|
databaseResponse, err := client.NewDatabase(testDatabaseName)
|
||||||
assert.Nil(t, err)
|
assert.Nil(t, err)
|
||||||
|
|||||||
@@ -6,14 +6,14 @@ import (
|
|||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/http/httptest"
|
|
||||||
"reflect"
|
"reflect"
|
||||||
|
"sync"
|
||||||
"testing"
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
|
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
|
||||||
"github.com/Azure/azure-sdk-for-go/sdk/data/azcosmos"
|
"github.com/Azure/azure-sdk-for-go/sdk/data/azcosmos"
|
||||||
"github.com/pikami/cosmium/api/config"
|
"github.com/pikami/cosmium/api/config"
|
||||||
"github.com/pikami/cosmium/internal/repositories"
|
|
||||||
repositorymodels "github.com/pikami/cosmium/internal/repository_models"
|
repositorymodels "github.com/pikami/cosmium/internal/repository_models"
|
||||||
"github.com/stretchr/testify/assert"
|
"github.com/stretchr/testify/assert"
|
||||||
)
|
)
|
||||||
@@ -53,9 +53,11 @@ func testCosmosQuery(t *testing.T,
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func documents_InitializeDb(t *testing.T) (*httptest.Server, *azcosmos.ContainerClient) {
|
func documents_InitializeDb(t *testing.T) (*TestServer, *azcosmos.ContainerClient) {
|
||||||
repositories.CreateDatabase(repositorymodels.Database{ID: testDatabaseName})
|
ts := runTestServer()
|
||||||
repositories.CreateCollection(testDatabaseName, repositorymodels.Collection{
|
|
||||||
|
ts.Repository.CreateDatabase(repositorymodels.Database{ID: testDatabaseName})
|
||||||
|
ts.Repository.CreateCollection(testDatabaseName, repositorymodels.Collection{
|
||||||
ID: testCollectionName,
|
ID: testCollectionName,
|
||||||
PartitionKey: struct {
|
PartitionKey: struct {
|
||||||
Paths []string "json:\"paths\""
|
Paths []string "json:\"paths\""
|
||||||
@@ -65,13 +67,11 @@ func documents_InitializeDb(t *testing.T) (*httptest.Server, *azcosmos.Container
|
|||||||
Paths: []string{"/pk"},
|
Paths: []string{"/pk"},
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
repositories.CreateDocument(testDatabaseName, testCollectionName, map[string]interface{}{"id": "12345", "pk": "123", "isCool": false, "arr": []int{1, 2, 3}})
|
ts.Repository.CreateDocument(testDatabaseName, testCollectionName, map[string]interface{}{"id": "12345", "pk": "123", "isCool": false, "arr": []int{1, 2, 3}})
|
||||||
repositories.CreateDocument(testDatabaseName, testCollectionName, map[string]interface{}{"id": "67890", "pk": "456", "isCool": true, "arr": []int{6, 7, 8}})
|
ts.Repository.CreateDocument(testDatabaseName, testCollectionName, map[string]interface{}{"id": "67890", "pk": "456", "isCool": true, "arr": []int{6, 7, 8}})
|
||||||
|
|
||||||
ts := runTestServer()
|
|
||||||
|
|
||||||
client, err := azcosmos.NewClientFromConnectionString(
|
client, err := azcosmos.NewClientFromConnectionString(
|
||||||
fmt.Sprintf("AccountEndpoint=%s;AccountKey=%s", ts.URL, config.Config.AccountKey),
|
fmt.Sprintf("AccountEndpoint=%s;AccountKey=%s", ts.URL, config.DefaultAccountKey),
|
||||||
&azcosmos.ClientOptions{},
|
&azcosmos.ClientOptions{},
|
||||||
)
|
)
|
||||||
assert.Nil(t, err)
|
assert.Nil(t, err)
|
||||||
@@ -84,7 +84,7 @@ func documents_InitializeDb(t *testing.T) (*httptest.Server, *azcosmos.Container
|
|||||||
|
|
||||||
func Test_Documents(t *testing.T) {
|
func Test_Documents(t *testing.T) {
|
||||||
ts, collectionClient := documents_InitializeDb(t)
|
ts, collectionClient := documents_InitializeDb(t)
|
||||||
defer ts.Close()
|
defer ts.Server.Close()
|
||||||
|
|
||||||
t.Run("Should query document", func(t *testing.T) {
|
t.Run("Should query document", func(t *testing.T) {
|
||||||
testCosmosQuery(t, collectionClient,
|
testCosmosQuery(t, collectionClient,
|
||||||
@@ -147,6 +147,21 @@ func Test_Documents(t *testing.T) {
|
|||||||
)
|
)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
t.Run("Should query document with query parameters as accessor", func(t *testing.T) {
|
||||||
|
testCosmosQuery(t, collectionClient,
|
||||||
|
`select c.id
|
||||||
|
FROM c
|
||||||
|
WHERE c[@param]="67890"
|
||||||
|
ORDER BY c.id`,
|
||||||
|
[]azcosmos.QueryParameter{
|
||||||
|
{Name: "@param", Value: "id"},
|
||||||
|
},
|
||||||
|
[]interface{}{
|
||||||
|
map[string]interface{}{"id": "67890"},
|
||||||
|
},
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
t.Run("Should query array accessor", func(t *testing.T) {
|
t.Run("Should query array accessor", func(t *testing.T) {
|
||||||
testCosmosQuery(t, collectionClient,
|
testCosmosQuery(t, collectionClient,
|
||||||
`SELECT c.id,
|
`SELECT c.id,
|
||||||
@@ -162,19 +177,72 @@ func Test_Documents(t *testing.T) {
|
|||||||
},
|
},
|
||||||
)
|
)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
t.Run("Should handle parallel writes", func(t *testing.T) {
|
||||||
|
var wg sync.WaitGroup
|
||||||
|
rutineCount := 100
|
||||||
|
results := make(chan error, rutineCount)
|
||||||
|
|
||||||
|
createCall := func(i int) {
|
||||||
|
defer wg.Done()
|
||||||
|
item := map[string]interface{}{
|
||||||
|
"id": fmt.Sprintf("id-%d", i),
|
||||||
|
"pk": fmt.Sprintf("pk-%d", i),
|
||||||
|
"val": i,
|
||||||
|
}
|
||||||
|
bytes, err := json.Marshal(item)
|
||||||
|
if err != nil {
|
||||||
|
results <- err
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
_, err = collectionClient.CreateItem(
|
||||||
|
ctx,
|
||||||
|
azcosmos.PartitionKey{},
|
||||||
|
bytes,
|
||||||
|
&azcosmos.ItemOptions{
|
||||||
|
EnableContentResponseOnWrite: false,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
results <- err
|
||||||
|
|
||||||
|
collectionClient.ReadItem(ctx, azcosmos.PartitionKey{}, fmt.Sprintf("id-%d", i), nil)
|
||||||
|
collectionClient.DeleteItem(ctx, azcosmos.PartitionKey{}, fmt.Sprintf("id-%d", i), nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
for i := 0; i < rutineCount; i++ {
|
||||||
|
wg.Add(1)
|
||||||
|
go createCall(i)
|
||||||
|
}
|
||||||
|
|
||||||
|
wg.Wait()
|
||||||
|
close(results)
|
||||||
|
|
||||||
|
for err := range results {
|
||||||
|
if err != nil {
|
||||||
|
t.Errorf("Error creating item: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func Test_Documents_Patch(t *testing.T) {
|
func Test_Documents_Patch(t *testing.T) {
|
||||||
ts, collectionClient := documents_InitializeDb(t)
|
ts, collectionClient := documents_InitializeDb(t)
|
||||||
defer ts.Close()
|
defer ts.Server.Close()
|
||||||
|
|
||||||
t.Run("Should PATCH document", func(t *testing.T) {
|
t.Run("Should PATCH document", func(t *testing.T) {
|
||||||
context := context.TODO()
|
context := context.TODO()
|
||||||
expectedData := map[string]interface{}{"id": "67890", "pk": "456", "newField": "newValue"}
|
expectedData := map[string]interface{}{"id": "67890", "pk": "666", "newField": "newValue", "incr": 15., "setted": "isSet"}
|
||||||
|
|
||||||
patch := azcosmos.PatchOperations{}
|
patch := azcosmos.PatchOperations{}
|
||||||
patch.AppendAdd("/newField", "newValue")
|
patch.AppendAdd("/newField", "newValue")
|
||||||
|
patch.AppendIncrement("/incr", 15)
|
||||||
patch.AppendRemove("/isCool")
|
patch.AppendRemove("/isCool")
|
||||||
|
patch.AppendReplace("/pk", "666")
|
||||||
|
patch.AppendSet("/setted", "isSet")
|
||||||
|
|
||||||
itemResponse, err := collectionClient.PatchItem(
|
itemResponse, err := collectionClient.PatchItem(
|
||||||
context,
|
context,
|
||||||
@@ -187,13 +255,15 @@ func Test_Documents_Patch(t *testing.T) {
|
|||||||
)
|
)
|
||||||
assert.Nil(t, err)
|
assert.Nil(t, err)
|
||||||
|
|
||||||
var itemResponseBody map[string]string
|
var itemResponseBody map[string]interface{}
|
||||||
json.Unmarshal(itemResponse.Value, &itemResponseBody)
|
json.Unmarshal(itemResponse.Value, &itemResponseBody)
|
||||||
|
|
||||||
assert.Equal(t, expectedData["id"], itemResponseBody["id"])
|
assert.Equal(t, expectedData["id"], itemResponseBody["id"])
|
||||||
assert.Equal(t, expectedData["pk"], itemResponseBody["pk"])
|
assert.Equal(t, expectedData["pk"], itemResponseBody["pk"])
|
||||||
assert.Empty(t, itemResponseBody["isCool"])
|
assert.Empty(t, itemResponseBody["isCool"])
|
||||||
assert.Equal(t, expectedData["newField"], itemResponseBody["newField"])
|
assert.Equal(t, expectedData["newField"], itemResponseBody["newField"])
|
||||||
|
assert.Equal(t, expectedData["incr"], itemResponseBody["incr"])
|
||||||
|
assert.Equal(t, expectedData["setted"], itemResponseBody["setted"])
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("Should not allow to PATCH document ID", func(t *testing.T) {
|
t.Run("Should not allow to PATCH document ID", func(t *testing.T) {
|
||||||
|
|||||||
@@ -15,14 +15,14 @@ import (
|
|||||||
// Request document with trailing slash like python cosmosdb client does.
|
// Request document with trailing slash like python cosmosdb client does.
|
||||||
func Test_Documents_Read_Trailing_Slash(t *testing.T) {
|
func Test_Documents_Read_Trailing_Slash(t *testing.T) {
|
||||||
ts, _ := documents_InitializeDb(t)
|
ts, _ := documents_InitializeDb(t)
|
||||||
defer ts.Close()
|
defer ts.Server.Close()
|
||||||
|
|
||||||
t.Run("Read doc with client that appends slash to path", func(t *testing.T) {
|
t.Run("Read doc with client that appends slash to path", func(t *testing.T) {
|
||||||
resourceIdTemplate := "dbs/%s/colls/%s/docs/%s"
|
resourceIdTemplate := "dbs/%s/colls/%s/docs/%s"
|
||||||
path := fmt.Sprintf(resourceIdTemplate, testDatabaseName, testCollectionName, "12345")
|
path := fmt.Sprintf(resourceIdTemplate, testDatabaseName, testCollectionName, "12345")
|
||||||
testUrl := ts.URL + "/" + path + "/"
|
testUrl := ts.URL + "/" + path + "/"
|
||||||
date := time.Now().Format(time.RFC1123)
|
date := time.Now().Format(time.RFC1123)
|
||||||
signature := authentication.GenerateSignature("GET", "docs", path, date, config.Config.AccountKey)
|
signature := authentication.GenerateSignature("GET", "docs", path, date, config.DefaultAccountKey)
|
||||||
httpClient := &http.Client{}
|
httpClient := &http.Client{}
|
||||||
req, _ := http.NewRequest("GET", testUrl, nil)
|
req, _ := http.NewRequest("GET", testUrl, nil)
|
||||||
req.Header.Add("x-ms-date", date)
|
req.Header.Add("x-ms-date", date)
|
||||||
|
|||||||
40
cmd/server/server.go
Normal file
40
cmd/server/server.go
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"os/signal"
|
||||||
|
"syscall"
|
||||||
|
|
||||||
|
"github.com/pikami/cosmium/api"
|
||||||
|
"github.com/pikami/cosmium/api/config"
|
||||||
|
"github.com/pikami/cosmium/internal/repositories"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
configuration := config.ParseFlags()
|
||||||
|
|
||||||
|
repository := repositories.NewDataRepository(repositories.RepositoryOptions{
|
||||||
|
InitialDataFilePath: configuration.InitialDataFilePath,
|
||||||
|
PersistDataFilePath: configuration.PersistDataFilePath,
|
||||||
|
})
|
||||||
|
|
||||||
|
server := api.NewApiServer(repository, configuration)
|
||||||
|
server.Start()
|
||||||
|
|
||||||
|
waitForExit(server, repository, configuration)
|
||||||
|
}
|
||||||
|
|
||||||
|
func waitForExit(server *api.ApiServer, repository *repositories.DataRepository, config config.ServerConfig) {
|
||||||
|
sigs := make(chan os.Signal, 1)
|
||||||
|
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
|
||||||
|
|
||||||
|
// Block until a exit signal is received
|
||||||
|
<-sigs
|
||||||
|
|
||||||
|
// Stop the server
|
||||||
|
server.Stop()
|
||||||
|
|
||||||
|
if config.PersistDataFilePath != "" {
|
||||||
|
repository.SaveStateFS(config.PersistDataFilePath)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -18,8 +18,8 @@ Cosmium strives to support the core features of Cosmos DB, including:
|
|||||||
|
|
||||||
| Feature | Implemented |
|
| Feature | Implemented |
|
||||||
| ----------------------------- | ----------- |
|
| ----------------------------- | ----------- |
|
||||||
| Subqueries | No |
|
| Subqueries | Yes |
|
||||||
| Joins | No |
|
| Joins | Yes |
|
||||||
| Computed properties | No |
|
| Computed properties | No |
|
||||||
| Coalesce operators | No |
|
| Coalesce operators | No |
|
||||||
| Bitwise operators | No |
|
| Bitwise operators | No |
|
||||||
@@ -62,16 +62,18 @@ Cosmium strives to support the core features of Cosmos DB, including:
|
|||||||
|
|
||||||
### Array Functions
|
### Array Functions
|
||||||
|
|
||||||
| Function | Implemented |
|
| Function | Implemented |
|
||||||
| -------------- | ----------- |
|
| ------------------ | ----------- |
|
||||||
| ARRAY_CONCAT | Yes |
|
| ARRAY_CONCAT | Yes |
|
||||||
| ARRAY_CONTAINS | No |
|
| ARRAY_CONTAINS | No |
|
||||||
| ARRAY_LENGTH | Yes |
|
| ARRAY_CONTAINS_ANY | No |
|
||||||
| ARRAY_SLICE | Yes |
|
| ARRAY_CONTAINS_ALL | No |
|
||||||
| CHOOSE | No |
|
| ARRAY_LENGTH | Yes |
|
||||||
| ObjectToArray | No |
|
| ARRAY_SLICE | Yes |
|
||||||
| SetIntersect | Yes |
|
| CHOOSE | No |
|
||||||
| SetUnion | Yes |
|
| ObjectToArray | No |
|
||||||
|
| SetIntersect | Yes |
|
||||||
|
| SetUnion | Yes |
|
||||||
|
|
||||||
### Conditional Functions
|
### Conditional Functions
|
||||||
|
|
||||||
|
|||||||
32
go.mod
32
go.mod
@@ -1,47 +1,47 @@
|
|||||||
module github.com/pikami/cosmium
|
module github.com/pikami/cosmium
|
||||||
|
|
||||||
go 1.21.6
|
go 1.22.0
|
||||||
|
|
||||||
require (
|
require (
|
||||||
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.9.2
|
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.9.2
|
||||||
github.com/Azure/azure-sdk-for-go/sdk/data/azcosmos v0.3.6
|
github.com/Azure/azure-sdk-for-go/sdk/data/azcosmos v0.3.6
|
||||||
github.com/evanphx/json-patch/v5 v5.9.0
|
|
||||||
github.com/gin-gonic/gin v1.10.0
|
github.com/gin-gonic/gin v1.10.0
|
||||||
github.com/google/uuid v1.6.0
|
github.com/google/uuid v1.6.0
|
||||||
|
github.com/pikami/json-patch/v5 v5.9.2
|
||||||
github.com/stretchr/testify v1.9.0
|
github.com/stretchr/testify v1.9.0
|
||||||
golang.org/x/exp v0.0.0-20240531132922-fd00a4e0eefc
|
golang.org/x/exp v0.0.0-20241217172543-b2144cdd0a67
|
||||||
)
|
)
|
||||||
|
|
||||||
require (
|
require (
|
||||||
github.com/Azure/azure-sdk-for-go v68.0.0+incompatible // indirect
|
github.com/Azure/azure-sdk-for-go v68.0.0+incompatible // indirect
|
||||||
github.com/Azure/azure-sdk-for-go/sdk/internal v1.5.2 // indirect
|
github.com/Azure/azure-sdk-for-go/sdk/internal v1.5.2 // indirect
|
||||||
github.com/bytedance/sonic v1.11.8 // indirect
|
github.com/bytedance/sonic v1.12.6 // indirect
|
||||||
github.com/bytedance/sonic/loader v0.1.1 // indirect
|
github.com/bytedance/sonic/loader v0.2.1 // indirect
|
||||||
github.com/cloudwego/base64x v0.1.4 // indirect
|
github.com/cloudwego/base64x v0.1.4 // indirect
|
||||||
github.com/cloudwego/iasm v0.2.0 // indirect
|
github.com/cloudwego/iasm v0.2.0 // indirect
|
||||||
github.com/davecgh/go-spew v1.1.1 // indirect
|
github.com/davecgh/go-spew v1.1.1 // indirect
|
||||||
github.com/gabriel-vasile/mimetype v1.4.4 // indirect
|
github.com/gabriel-vasile/mimetype v1.4.7 // indirect
|
||||||
github.com/gin-contrib/sse v0.1.0 // indirect
|
github.com/gin-contrib/sse v0.1.0 // indirect
|
||||||
github.com/go-playground/locales v0.14.1 // indirect
|
github.com/go-playground/locales v0.14.1 // indirect
|
||||||
github.com/go-playground/universal-translator v0.18.1 // indirect
|
github.com/go-playground/universal-translator v0.18.1 // indirect
|
||||||
github.com/go-playground/validator/v10 v10.21.0 // indirect
|
github.com/go-playground/validator/v10 v10.23.0 // indirect
|
||||||
github.com/goccy/go-json v0.10.3 // indirect
|
github.com/goccy/go-json v0.10.4 // indirect
|
||||||
github.com/json-iterator/go v1.1.12 // indirect
|
github.com/json-iterator/go v1.1.12 // indirect
|
||||||
github.com/klauspost/cpuid/v2 v2.2.7 // indirect
|
github.com/klauspost/cpuid/v2 v2.2.9 // indirect
|
||||||
github.com/leodido/go-urn v1.4.0 // indirect
|
github.com/leodido/go-urn v1.4.0 // indirect
|
||||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
|
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
|
||||||
github.com/modern-go/reflect2 v1.0.2 // indirect
|
github.com/modern-go/reflect2 v1.0.2 // indirect
|
||||||
github.com/pelletier/go-toml/v2 v2.2.2 // indirect
|
github.com/pelletier/go-toml/v2 v2.2.3 // indirect
|
||||||
github.com/pkg/errors v0.9.1 // indirect
|
github.com/pkg/errors v0.9.1 // indirect
|
||||||
github.com/pmezard/go-difflib v1.0.0 // indirect
|
github.com/pmezard/go-difflib v1.0.0 // indirect
|
||||||
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
|
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
|
||||||
github.com/ugorji/go/codec v1.2.12 // indirect
|
github.com/ugorji/go/codec v1.2.12 // indirect
|
||||||
golang.org/x/arch v0.8.0 // indirect
|
golang.org/x/arch v0.12.0 // indirect
|
||||||
golang.org/x/crypto v0.23.0 // indirect
|
golang.org/x/crypto v0.31.0 // indirect
|
||||||
golang.org/x/net v0.25.0 // indirect
|
golang.org/x/net v0.33.0 // indirect
|
||||||
golang.org/x/sys v0.20.0 // indirect
|
golang.org/x/sys v0.28.0 // indirect
|
||||||
golang.org/x/text v0.15.0 // indirect
|
golang.org/x/text v0.21.0 // indirect
|
||||||
google.golang.org/protobuf v1.34.1 // indirect
|
google.golang.org/protobuf v1.36.0 // indirect
|
||||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||||
)
|
)
|
||||||
|
|||||||
64
go.sum
64
go.sum
@@ -10,10 +10,11 @@ github.com/Azure/azure-sdk-for-go/sdk/internal v1.5.2 h1:LqbJ/WzJUwBf8UiaSzgX7aM
|
|||||||
github.com/Azure/azure-sdk-for-go/sdk/internal v1.5.2/go.mod h1:yInRyqWXAuaPrgI7p70+lDDgh3mlBohis29jGMISnmc=
|
github.com/Azure/azure-sdk-for-go/sdk/internal v1.5.2/go.mod h1:yInRyqWXAuaPrgI7p70+lDDgh3mlBohis29jGMISnmc=
|
||||||
github.com/AzureAD/microsoft-authentication-library-for-go v0.4.0 h1:WVsrXCnHlDDX8ls+tootqRE87/hL9S/g4ewig9RsD/c=
|
github.com/AzureAD/microsoft-authentication-library-for-go v0.4.0 h1:WVsrXCnHlDDX8ls+tootqRE87/hL9S/g4ewig9RsD/c=
|
||||||
github.com/AzureAD/microsoft-authentication-library-for-go v0.4.0/go.mod h1:Vt9sXTKwMyGcOxSmLDMnGPgqsUg7m8pe215qMLrDXw4=
|
github.com/AzureAD/microsoft-authentication-library-for-go v0.4.0/go.mod h1:Vt9sXTKwMyGcOxSmLDMnGPgqsUg7m8pe215qMLrDXw4=
|
||||||
github.com/bytedance/sonic v1.11.8 h1:Zw/j1KfiS+OYTi9lyB3bb0CFxPJVkM17k1wyDG32LRA=
|
github.com/bytedance/sonic v1.12.6 h1:/isNmCUF2x3Sh8RAp/4mh4ZGkcFAX/hLrzrK3AvpRzk=
|
||||||
github.com/bytedance/sonic v1.11.8/go.mod h1:LysEHSvpvDySVdC2f87zGWf6CIKJcAvqab1ZaiQtds4=
|
github.com/bytedance/sonic v1.12.6/go.mod h1:B8Gt/XvtZ3Fqj+iSKMypzymZxw/FVwgIGKzMzT9r/rk=
|
||||||
github.com/bytedance/sonic/loader v0.1.1 h1:c+e5Pt1k/cy5wMveRDyk2X4B9hF4g7an8N3zCYjJFNM=
|
|
||||||
github.com/bytedance/sonic/loader v0.1.1/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU=
|
github.com/bytedance/sonic/loader v0.1.1/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU=
|
||||||
|
github.com/bytedance/sonic/loader v0.2.1 h1:1GgorWTqf12TA8mma4DDSbaQigE2wOgQo7iCjjJv3+E=
|
||||||
|
github.com/bytedance/sonic/loader v0.2.1/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU=
|
||||||
github.com/cloudwego/base64x v0.1.4 h1:jwCgWpFanWmN8xoIUHa2rtzmkd5J2plF/dnLS6Xd/0Y=
|
github.com/cloudwego/base64x v0.1.4 h1:jwCgWpFanWmN8xoIUHa2rtzmkd5J2plF/dnLS6Xd/0Y=
|
||||||
github.com/cloudwego/base64x v0.1.4/go.mod h1:0zlkT4Wn5C6NdauXdJRhSKRlJvmclQ1hhJgA0rcu/8w=
|
github.com/cloudwego/base64x v0.1.4/go.mod h1:0zlkT4Wn5C6NdauXdJRhSKRlJvmclQ1hhJgA0rcu/8w=
|
||||||
github.com/cloudwego/iasm v0.2.0 h1:1KNIy1I1H9hNNFEEH3DVnI4UujN+1zjpuk6gwHLTssg=
|
github.com/cloudwego/iasm v0.2.0 h1:1KNIy1I1H9hNNFEEH3DVnI4UujN+1zjpuk6gwHLTssg=
|
||||||
@@ -21,10 +22,8 @@ github.com/cloudwego/iasm v0.2.0/go.mod h1:8rXZaNYT2n95jn+zTI1sDr+IgcD2GVs0nlbbQ
|
|||||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
github.com/evanphx/json-patch/v5 v5.9.0 h1:kcBlZQbplgElYIlo/n1hJbls2z/1awpXxpRi0/FOJfg=
|
github.com/gabriel-vasile/mimetype v1.4.7 h1:SKFKl7kD0RiPdbht0s7hFtjl489WcQ1VyPW8ZzUMYCA=
|
||||||
github.com/evanphx/json-patch/v5 v5.9.0/go.mod h1:VNkHZ/282BpEyt/tObQO8s5CMPmYYq14uClGH4abBuQ=
|
github.com/gabriel-vasile/mimetype v1.4.7/go.mod h1:GDlAgAyIRT27BhFl53XNAFtfjzOkLaF35JdEG0P7LtU=
|
||||||
github.com/gabriel-vasile/mimetype v1.4.4 h1:QjV6pZ7/XZ7ryI2KuyeEDE8wnh7fHP9YnQy+R0LnH8I=
|
|
||||||
github.com/gabriel-vasile/mimetype v1.4.4/go.mod h1:JwLei5XPtWdGiMFB5Pjle1oEeoSeEuJfJE+TtfvdB/s=
|
|
||||||
github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE=
|
github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE=
|
||||||
github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=
|
github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=
|
||||||
github.com/gin-gonic/gin v1.10.0 h1:nTuyha1TYqgedzytsKYqna+DfLos46nTv2ygFy86HFU=
|
github.com/gin-gonic/gin v1.10.0 h1:nTuyha1TYqgedzytsKYqna+DfLos46nTv2ygFy86HFU=
|
||||||
@@ -35,10 +34,10 @@ github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/o
|
|||||||
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
|
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
|
||||||
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
|
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
|
||||||
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
|
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
|
||||||
github.com/go-playground/validator/v10 v10.21.0 h1:4fZA11ovvtkdgaeev9RGWPgc1uj3H8W+rNYyH/ySBb0=
|
github.com/go-playground/validator/v10 v10.23.0 h1:/PwmTwZhS0dPkav3cdK9kV1FsAmrL8sThn8IHr/sO+o=
|
||||||
github.com/go-playground/validator/v10 v10.21.0/go.mod h1:dbuPbCMFw/DrkbEynArYaCwl3amGuJotoKCe95atGMM=
|
github.com/go-playground/validator/v10 v10.23.0/go.mod h1:dbuPbCMFw/DrkbEynArYaCwl3amGuJotoKCe95atGMM=
|
||||||
github.com/goccy/go-json v0.10.3 h1:KZ5WoDbxAIgm2HNbYckL0se1fHD6rz5j4ywS6ebzDqA=
|
github.com/goccy/go-json v0.10.4 h1:JSwxQzIqKfmFX1swYPpUThQZp/Ka4wzJdK0LWVytLPM=
|
||||||
github.com/goccy/go-json v0.10.3/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=
|
github.com/goccy/go-json v0.10.4/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=
|
||||||
github.com/golang-jwt/jwt v3.2.1+incompatible h1:73Z+4BJcrTC+KczS6WvTPvRGOp1WmfEP4Q1lOd9Z/+c=
|
github.com/golang-jwt/jwt v3.2.1+incompatible h1:73Z+4BJcrTC+KczS6WvTPvRGOp1WmfEP4Q1lOd9Z/+c=
|
||||||
github.com/golang-jwt/jwt v3.2.1+incompatible/go.mod h1:8pz2t5EyA70fFQQSrl6XZXzqecmYZeUEB8OUGHkxJ+I=
|
github.com/golang-jwt/jwt v3.2.1+incompatible/go.mod h1:8pz2t5EyA70fFQQSrl6XZXzqecmYZeUEB8OUGHkxJ+I=
|
||||||
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
|
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
|
||||||
@@ -49,8 +48,8 @@ github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+
|
|||||||
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
|
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
|
||||||
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
|
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
|
||||||
github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
|
github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
|
||||||
github.com/klauspost/cpuid/v2 v2.2.7 h1:ZWSB3igEs+d0qvnxR/ZBzXVmxkgt8DdzP6m9pfuVLDM=
|
github.com/klauspost/cpuid/v2 v2.2.9 h1:66ze0taIn2H33fBvCkXuv9BmCwDfafmiIVpKV9kKGuY=
|
||||||
github.com/klauspost/cpuid/v2 v2.2.7/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws=
|
github.com/klauspost/cpuid/v2 v2.2.9/go.mod h1:rqkxqrZ1EhYM9G+hXH7YdowN5R5RGN6NK4QwQ3WMXF8=
|
||||||
github.com/knz/go-libedit v1.10.1/go.mod h1:MZTVkCWyz0oBc7JOWP3wNAzd002ZbM/5hgShxwh4x8M=
|
github.com/knz/go-libedit v1.10.1/go.mod h1:MZTVkCWyz0oBc7JOWP3wNAzd002ZbM/5hgShxwh4x8M=
|
||||||
github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc=
|
github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc=
|
||||||
github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw=
|
github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw=
|
||||||
@@ -63,8 +62,10 @@ github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w
|
|||||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||||
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
|
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
|
||||||
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
|
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
|
||||||
github.com/pelletier/go-toml/v2 v2.2.2 h1:aYUidT7k73Pcl9nb2gScu7NSrKCSHIDE89b3+6Wq+LM=
|
github.com/pelletier/go-toml/v2 v2.2.3 h1:YmeHyLY8mFWbdkNWwpr+qIL2bEqT0o95WSdkNHvL12M=
|
||||||
github.com/pelletier/go-toml/v2 v2.2.2/go.mod h1:1t835xjRzz80PqgE6HHgN2JOsmgYu/h4qDAS4n929Rs=
|
github.com/pelletier/go-toml/v2 v2.2.3/go.mod h1:MfCQTFTvCcUyyvvwm1+G6H/jORL20Xlb6rzQu9GuUkc=
|
||||||
|
github.com/pikami/json-patch/v5 v5.9.2 h1:ciTlocWccYVE3DEa45dsMm02c/tOvcaBY7PpEUNZhrU=
|
||||||
|
github.com/pikami/json-patch/v5 v5.9.2/go.mod h1:eJIScZ4xgf2aBHLi2UMzYtjlWESUBDOBf7EAx3JW0nI=
|
||||||
github.com/pkg/browser v0.0.0-20210115035449-ce105d075bb4 h1:Qj1ukM4GlMWXNdMBuXcXfz/Kw9s1qm0CLY32QxuSImI=
|
github.com/pkg/browser v0.0.0-20210115035449-ce105d075bb4 h1:Qj1ukM4GlMWXNdMBuXcXfz/Kw9s1qm0CLY32QxuSImI=
|
||||||
github.com/pkg/browser v0.0.0-20210115035449-ce105d075bb4/go.mod h1:N6UoU20jOqggOuDwUaBQpluzLNDqif3kq9z2wpdYEfQ=
|
github.com/pkg/browser v0.0.0-20210115035449-ce105d075bb4/go.mod h1:N6UoU20jOqggOuDwUaBQpluzLNDqif3kq9z2wpdYEfQ=
|
||||||
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
|
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
|
||||||
@@ -74,40 +75,35 @@ github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZN
|
|||||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||||
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
||||||
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
|
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
|
||||||
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
|
|
||||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||||
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||||
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
|
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
|
||||||
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
|
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
|
||||||
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
|
|
||||||
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
|
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
|
||||||
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
|
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
|
||||||
github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
|
github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
|
||||||
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
|
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
|
||||||
github.com/ugorji/go/codec v1.2.12 h1:9LC83zGrHhuUA9l16C9AHXAqEV/2wBQ4nkvumAE65EE=
|
github.com/ugorji/go/codec v1.2.12 h1:9LC83zGrHhuUA9l16C9AHXAqEV/2wBQ4nkvumAE65EE=
|
||||||
github.com/ugorji/go/codec v1.2.12/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg=
|
github.com/ugorji/go/codec v1.2.12/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg=
|
||||||
golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=
|
golang.org/x/arch v0.12.0 h1:UsYJhbzPYGsT0HbEdmYcqtCv8UNGvnaL561NnIUvaKg=
|
||||||
golang.org/x/arch v0.8.0 h1:3wRIsP3pM4yUptoR96otTUOXI367OS0+c9eeRi9doIc=
|
golang.org/x/arch v0.12.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys=
|
||||||
golang.org/x/arch v0.8.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys=
|
golang.org/x/crypto v0.31.0 h1:ihbySMvVjLAeSH1IbfcRTkD/iNscyz8rGzjF/E5hV6U=
|
||||||
golang.org/x/crypto v0.23.0 h1:dIJU/v2J8Mdglj/8rJ6UUOM3Zc9zLZxVZwwxMooUSAI=
|
golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk=
|
||||||
golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8=
|
golang.org/x/exp v0.0.0-20241217172543-b2144cdd0a67 h1:1UoZQm6f0P/ZO0w1Ri+f+ifG/gXhegadRdwBIXEFWDo=
|
||||||
golang.org/x/exp v0.0.0-20240531132922-fd00a4e0eefc h1:O9NuF4s+E/PvMIy+9IUZB9znFwUIXEWSstNjek6VpVg=
|
golang.org/x/exp v0.0.0-20241217172543-b2144cdd0a67/go.mod h1:qj5a5QZpwLU2NLQudwIN5koi3beDhSAlJwa67PuM98c=
|
||||||
golang.org/x/exp v0.0.0-20240531132922-fd00a4e0eefc/go.mod h1:XtvwrStGgqGPLc4cjQfWqZHG1YFdYs6swckp8vpsjnc=
|
golang.org/x/net v0.33.0 h1:74SYHlV8BIgHIFC/LrYkOGIwL19eTYXQ5wc6TBuO36I=
|
||||||
golang.org/x/net v0.25.0 h1:d/OCCoBEUq33pjydKrGQhw7IlUPI2Oylr+8qLx49kac=
|
golang.org/x/net v0.33.0/go.mod h1:HXLR5J+9DxmrqMwG9qjGCxZ+zKXxBru04zlTvWlWuN4=
|
||||||
golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM=
|
|
||||||
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
|
||||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
golang.org/x/sys v0.20.0 h1:Od9JTbYCk261bKm4M/mw7AklTlFYIa0bIp9BgSm1S8Y=
|
golang.org/x/sys v0.28.0 h1:Fksou7UEQUWlKvIdsqzJmUmCX3cZuD2+P3XyyzwMhlA=
|
||||||
golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||||
golang.org/x/text v0.15.0 h1:h1V/4gjBv8v9cjcR6+AR5+/cIYK5N/WAgiv4xlsEtAk=
|
golang.org/x/text v0.21.0 h1:zyQAAkrwaneQ066sspRyJaG9VNi/YJ1NfzcGB3hZ/qo=
|
||||||
golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
|
golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ=
|
||||||
google.golang.org/protobuf v1.34.1 h1:9ddQBjfCyZPOHPUiPxpYESBLc+T8P3E+Vo4IbKZgFWg=
|
google.golang.org/protobuf v1.36.0 h1:mjIs9gYtt56AzC4ZaffQuh88TZurBGhIJMBZGSxNerQ=
|
||||||
google.golang.org/protobuf v1.34.1/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos=
|
google.golang.org/protobuf v1.36.0/go.mod h1:9fA7Ob0pmnwhb644+1+CVWFRbNajQ6iRojtC/QF5bRE=
|
||||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
|
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
|
||||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
nullprogram.com/x/optparse v1.0.0/go.mod h1:KdyPE+Igbe0jQUrVfMqDMeJQIJZEuyV7pjYmp6pbG50=
|
nullprogram.com/x/optparse v1.0.0/go.mod h1:KdyPE+Igbe0jQUrVfMqDMeJQIJZEuyV7pjYmp6pbG50=
|
||||||
rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4=
|
|
||||||
|
|||||||
@@ -3,22 +3,22 @@ package logger
|
|||||||
import (
|
import (
|
||||||
"log"
|
"log"
|
||||||
"os"
|
"os"
|
||||||
|
|
||||||
"github.com/pikami/cosmium/api/config"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
|
var EnableDebugOutput = false
|
||||||
|
|
||||||
var DebugLogger = log.New(os.Stdout, "", log.Ldate|log.Ltime|log.Lshortfile)
|
var DebugLogger = log.New(os.Stdout, "", log.Ldate|log.Ltime|log.Lshortfile)
|
||||||
var InfoLogger = log.New(os.Stdout, "", log.Ldate|log.Ltime)
|
var InfoLogger = log.New(os.Stdout, "", log.Ldate|log.Ltime)
|
||||||
var ErrorLogger = log.New(os.Stderr, "", log.Ldate|log.Ltime|log.Lshortfile)
|
var ErrorLogger = log.New(os.Stderr, "", log.Ldate|log.Ltime|log.Lshortfile)
|
||||||
|
|
||||||
func Debug(v ...any) {
|
func Debug(v ...any) {
|
||||||
if config.Config.Debug {
|
if EnableDebugOutput {
|
||||||
DebugLogger.Println(v...)
|
DebugLogger.Println(v...)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func Debugf(format string, v ...any) {
|
func Debugf(format string, v ...any) {
|
||||||
if config.Config.Debug {
|
if EnableDebugOutput {
|
||||||
DebugLogger.Printf(format, v...)
|
DebugLogger.Printf(format, v...)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,48 +11,60 @@ import (
|
|||||||
"golang.org/x/exp/maps"
|
"golang.org/x/exp/maps"
|
||||||
)
|
)
|
||||||
|
|
||||||
func GetAllCollections(databaseId string) ([]repositorymodels.Collection, repositorymodels.RepositoryStatus) {
|
func (r *DataRepository) GetAllCollections(databaseId string) ([]repositorymodels.Collection, repositorymodels.RepositoryStatus) {
|
||||||
if _, ok := storeState.Databases[databaseId]; !ok {
|
r.storeState.RLock()
|
||||||
|
defer r.storeState.RUnlock()
|
||||||
|
|
||||||
|
if _, ok := r.storeState.Databases[databaseId]; !ok {
|
||||||
return make([]repositorymodels.Collection, 0), repositorymodels.StatusNotFound
|
return make([]repositorymodels.Collection, 0), repositorymodels.StatusNotFound
|
||||||
}
|
}
|
||||||
|
|
||||||
return maps.Values(storeState.Collections[databaseId]), repositorymodels.StatusOk
|
return maps.Values(r.storeState.Collections[databaseId]), repositorymodels.StatusOk
|
||||||
}
|
}
|
||||||
|
|
||||||
func GetCollection(databaseId string, collectionId string) (repositorymodels.Collection, repositorymodels.RepositoryStatus) {
|
func (r *DataRepository) GetCollection(databaseId string, collectionId string) (repositorymodels.Collection, repositorymodels.RepositoryStatus) {
|
||||||
if _, ok := storeState.Databases[databaseId]; !ok {
|
r.storeState.RLock()
|
||||||
|
defer r.storeState.RUnlock()
|
||||||
|
|
||||||
|
if _, ok := r.storeState.Databases[databaseId]; !ok {
|
||||||
return repositorymodels.Collection{}, repositorymodels.StatusNotFound
|
return repositorymodels.Collection{}, repositorymodels.StatusNotFound
|
||||||
}
|
}
|
||||||
|
|
||||||
if _, ok := storeState.Collections[databaseId][collectionId]; !ok {
|
if _, ok := r.storeState.Collections[databaseId][collectionId]; !ok {
|
||||||
return repositorymodels.Collection{}, repositorymodels.StatusNotFound
|
return repositorymodels.Collection{}, repositorymodels.StatusNotFound
|
||||||
}
|
}
|
||||||
|
|
||||||
return storeState.Collections[databaseId][collectionId], repositorymodels.StatusOk
|
return r.storeState.Collections[databaseId][collectionId], repositorymodels.StatusOk
|
||||||
}
|
}
|
||||||
|
|
||||||
func DeleteCollection(databaseId string, collectionId string) repositorymodels.RepositoryStatus {
|
func (r *DataRepository) DeleteCollection(databaseId string, collectionId string) repositorymodels.RepositoryStatus {
|
||||||
if _, ok := storeState.Databases[databaseId]; !ok {
|
r.storeState.Lock()
|
||||||
|
defer r.storeState.Unlock()
|
||||||
|
|
||||||
|
if _, ok := r.storeState.Databases[databaseId]; !ok {
|
||||||
return repositorymodels.StatusNotFound
|
return repositorymodels.StatusNotFound
|
||||||
}
|
}
|
||||||
|
|
||||||
if _, ok := storeState.Collections[databaseId][collectionId]; !ok {
|
if _, ok := r.storeState.Collections[databaseId][collectionId]; !ok {
|
||||||
return repositorymodels.StatusNotFound
|
return repositorymodels.StatusNotFound
|
||||||
}
|
}
|
||||||
|
|
||||||
delete(storeState.Collections[databaseId], collectionId)
|
delete(r.storeState.Collections[databaseId], collectionId)
|
||||||
|
|
||||||
return repositorymodels.StatusOk
|
return repositorymodels.StatusOk
|
||||||
}
|
}
|
||||||
|
|
||||||
func CreateCollection(databaseId string, newCollection repositorymodels.Collection) (repositorymodels.Collection, repositorymodels.RepositoryStatus) {
|
func (r *DataRepository) CreateCollection(databaseId string, newCollection repositorymodels.Collection) (repositorymodels.Collection, repositorymodels.RepositoryStatus) {
|
||||||
|
r.storeState.Lock()
|
||||||
|
defer r.storeState.Unlock()
|
||||||
|
|
||||||
var ok bool
|
var ok bool
|
||||||
var database repositorymodels.Database
|
var database repositorymodels.Database
|
||||||
if database, ok = storeState.Databases[databaseId]; !ok {
|
if database, ok = r.storeState.Databases[databaseId]; !ok {
|
||||||
return repositorymodels.Collection{}, repositorymodels.StatusNotFound
|
return repositorymodels.Collection{}, repositorymodels.StatusNotFound
|
||||||
}
|
}
|
||||||
|
|
||||||
if _, ok = storeState.Collections[databaseId][newCollection.ID]; ok {
|
if _, ok = r.storeState.Collections[databaseId][newCollection.ID]; ok {
|
||||||
return repositorymodels.Collection{}, repositorymodels.Conflict
|
return repositorymodels.Collection{}, repositorymodels.Conflict
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -63,8 +75,8 @@ func CreateCollection(databaseId string, newCollection repositorymodels.Collecti
|
|||||||
newCollection.ETag = fmt.Sprintf("\"%s\"", uuid.New())
|
newCollection.ETag = fmt.Sprintf("\"%s\"", uuid.New())
|
||||||
newCollection.Self = fmt.Sprintf("dbs/%s/colls/%s/", database.ResourceID, newCollection.ResourceID)
|
newCollection.Self = fmt.Sprintf("dbs/%s/colls/%s/", database.ResourceID, newCollection.ResourceID)
|
||||||
|
|
||||||
storeState.Collections[databaseId][newCollection.ID] = newCollection
|
r.storeState.Collections[databaseId][newCollection.ID] = newCollection
|
||||||
storeState.Documents[databaseId][newCollection.ID] = make(map[string]repositorymodels.Document)
|
r.storeState.Documents[databaseId][newCollection.ID] = make(map[string]repositorymodels.Document)
|
||||||
|
|
||||||
return newCollection, repositorymodels.StatusOk
|
return newCollection, repositorymodels.StatusOk
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,30 +10,42 @@ import (
|
|||||||
"golang.org/x/exp/maps"
|
"golang.org/x/exp/maps"
|
||||||
)
|
)
|
||||||
|
|
||||||
func GetAllDatabases() ([]repositorymodels.Database, repositorymodels.RepositoryStatus) {
|
func (r *DataRepository) GetAllDatabases() ([]repositorymodels.Database, repositorymodels.RepositoryStatus) {
|
||||||
return maps.Values(storeState.Databases), repositorymodels.StatusOk
|
r.storeState.RLock()
|
||||||
|
defer r.storeState.RUnlock()
|
||||||
|
|
||||||
|
return maps.Values(r.storeState.Databases), repositorymodels.StatusOk
|
||||||
}
|
}
|
||||||
|
|
||||||
func GetDatabase(id string) (repositorymodels.Database, repositorymodels.RepositoryStatus) {
|
func (r *DataRepository) GetDatabase(id string) (repositorymodels.Database, repositorymodels.RepositoryStatus) {
|
||||||
if database, ok := storeState.Databases[id]; ok {
|
r.storeState.RLock()
|
||||||
|
defer r.storeState.RUnlock()
|
||||||
|
|
||||||
|
if database, ok := r.storeState.Databases[id]; ok {
|
||||||
return database, repositorymodels.StatusOk
|
return database, repositorymodels.StatusOk
|
||||||
}
|
}
|
||||||
|
|
||||||
return repositorymodels.Database{}, repositorymodels.StatusNotFound
|
return repositorymodels.Database{}, repositorymodels.StatusNotFound
|
||||||
}
|
}
|
||||||
|
|
||||||
func DeleteDatabase(id string) repositorymodels.RepositoryStatus {
|
func (r *DataRepository) DeleteDatabase(id string) repositorymodels.RepositoryStatus {
|
||||||
if _, ok := storeState.Databases[id]; !ok {
|
r.storeState.Lock()
|
||||||
|
defer r.storeState.Unlock()
|
||||||
|
|
||||||
|
if _, ok := r.storeState.Databases[id]; !ok {
|
||||||
return repositorymodels.StatusNotFound
|
return repositorymodels.StatusNotFound
|
||||||
}
|
}
|
||||||
|
|
||||||
delete(storeState.Databases, id)
|
delete(r.storeState.Databases, id)
|
||||||
|
|
||||||
return repositorymodels.StatusOk
|
return repositorymodels.StatusOk
|
||||||
}
|
}
|
||||||
|
|
||||||
func CreateDatabase(newDatabase repositorymodels.Database) (repositorymodels.Database, repositorymodels.RepositoryStatus) {
|
func (r *DataRepository) CreateDatabase(newDatabase repositorymodels.Database) (repositorymodels.Database, repositorymodels.RepositoryStatus) {
|
||||||
if _, ok := storeState.Databases[newDatabase.ID]; ok {
|
r.storeState.Lock()
|
||||||
|
defer r.storeState.Unlock()
|
||||||
|
|
||||||
|
if _, ok := r.storeState.Databases[newDatabase.ID]; ok {
|
||||||
return repositorymodels.Database{}, repositorymodels.Conflict
|
return repositorymodels.Database{}, repositorymodels.Conflict
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -42,9 +54,9 @@ func CreateDatabase(newDatabase repositorymodels.Database) (repositorymodels.Dat
|
|||||||
newDatabase.ETag = fmt.Sprintf("\"%s\"", uuid.New())
|
newDatabase.ETag = fmt.Sprintf("\"%s\"", uuid.New())
|
||||||
newDatabase.Self = fmt.Sprintf("dbs/%s/", newDatabase.ResourceID)
|
newDatabase.Self = fmt.Sprintf("dbs/%s/", newDatabase.ResourceID)
|
||||||
|
|
||||||
storeState.Databases[newDatabase.ID] = newDatabase
|
r.storeState.Databases[newDatabase.ID] = newDatabase
|
||||||
storeState.Collections[newDatabase.ID] = make(map[string]repositorymodels.Collection)
|
r.storeState.Collections[newDatabase.ID] = make(map[string]repositorymodels.Collection)
|
||||||
storeState.Documents[newDatabase.ID] = make(map[string]map[string]repositorymodels.Document)
|
r.storeState.Documents[newDatabase.ID] = make(map[string]map[string]repositorymodels.Document)
|
||||||
|
|
||||||
return newDatabase, repositorymodels.StatusOk
|
return newDatabase, repositorymodels.StatusOk
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -14,53 +14,65 @@ import (
|
|||||||
"golang.org/x/exp/maps"
|
"golang.org/x/exp/maps"
|
||||||
)
|
)
|
||||||
|
|
||||||
func GetAllDocuments(databaseId string, collectionId string) ([]repositorymodels.Document, repositorymodels.RepositoryStatus) {
|
func (r *DataRepository) GetAllDocuments(databaseId string, collectionId string) ([]repositorymodels.Document, repositorymodels.RepositoryStatus) {
|
||||||
if _, ok := storeState.Databases[databaseId]; !ok {
|
r.storeState.RLock()
|
||||||
|
defer r.storeState.RUnlock()
|
||||||
|
|
||||||
|
if _, ok := r.storeState.Databases[databaseId]; !ok {
|
||||||
return make([]repositorymodels.Document, 0), repositorymodels.StatusNotFound
|
return make([]repositorymodels.Document, 0), repositorymodels.StatusNotFound
|
||||||
}
|
}
|
||||||
|
|
||||||
if _, ok := storeState.Collections[databaseId][collectionId]; !ok {
|
if _, ok := r.storeState.Collections[databaseId][collectionId]; !ok {
|
||||||
return make([]repositorymodels.Document, 0), repositorymodels.StatusNotFound
|
return make([]repositorymodels.Document, 0), repositorymodels.StatusNotFound
|
||||||
}
|
}
|
||||||
|
|
||||||
return maps.Values(storeState.Documents[databaseId][collectionId]), repositorymodels.StatusOk
|
return maps.Values(r.storeState.Documents[databaseId][collectionId]), repositorymodels.StatusOk
|
||||||
}
|
}
|
||||||
|
|
||||||
func GetDocument(databaseId string, collectionId string, documentId string) (repositorymodels.Document, repositorymodels.RepositoryStatus) {
|
func (r *DataRepository) GetDocument(databaseId string, collectionId string, documentId string) (repositorymodels.Document, repositorymodels.RepositoryStatus) {
|
||||||
if _, ok := storeState.Databases[databaseId]; !ok {
|
r.storeState.RLock()
|
||||||
|
defer r.storeState.RUnlock()
|
||||||
|
|
||||||
|
if _, ok := r.storeState.Databases[databaseId]; !ok {
|
||||||
return repositorymodels.Document{}, repositorymodels.StatusNotFound
|
return repositorymodels.Document{}, repositorymodels.StatusNotFound
|
||||||
}
|
}
|
||||||
|
|
||||||
if _, ok := storeState.Collections[databaseId][collectionId]; !ok {
|
if _, ok := r.storeState.Collections[databaseId][collectionId]; !ok {
|
||||||
return repositorymodels.Document{}, repositorymodels.StatusNotFound
|
return repositorymodels.Document{}, repositorymodels.StatusNotFound
|
||||||
}
|
}
|
||||||
|
|
||||||
if _, ok := storeState.Documents[databaseId][collectionId][documentId]; !ok {
|
if _, ok := r.storeState.Documents[databaseId][collectionId][documentId]; !ok {
|
||||||
return repositorymodels.Document{}, repositorymodels.StatusNotFound
|
return repositorymodels.Document{}, repositorymodels.StatusNotFound
|
||||||
}
|
}
|
||||||
|
|
||||||
return storeState.Documents[databaseId][collectionId][documentId], repositorymodels.StatusOk
|
return r.storeState.Documents[databaseId][collectionId][documentId], repositorymodels.StatusOk
|
||||||
}
|
}
|
||||||
|
|
||||||
func DeleteDocument(databaseId string, collectionId string, documentId string) repositorymodels.RepositoryStatus {
|
func (r *DataRepository) DeleteDocument(databaseId string, collectionId string, documentId string) repositorymodels.RepositoryStatus {
|
||||||
if _, ok := storeState.Databases[databaseId]; !ok {
|
r.storeState.Lock()
|
||||||
|
defer r.storeState.Unlock()
|
||||||
|
|
||||||
|
if _, ok := r.storeState.Databases[databaseId]; !ok {
|
||||||
return repositorymodels.StatusNotFound
|
return repositorymodels.StatusNotFound
|
||||||
}
|
}
|
||||||
|
|
||||||
if _, ok := storeState.Collections[databaseId][collectionId]; !ok {
|
if _, ok := r.storeState.Collections[databaseId][collectionId]; !ok {
|
||||||
return repositorymodels.StatusNotFound
|
return repositorymodels.StatusNotFound
|
||||||
}
|
}
|
||||||
|
|
||||||
if _, ok := storeState.Documents[databaseId][collectionId][documentId]; !ok {
|
if _, ok := r.storeState.Documents[databaseId][collectionId][documentId]; !ok {
|
||||||
return repositorymodels.StatusNotFound
|
return repositorymodels.StatusNotFound
|
||||||
}
|
}
|
||||||
|
|
||||||
delete(storeState.Documents[databaseId][collectionId], documentId)
|
delete(r.storeState.Documents[databaseId][collectionId], documentId)
|
||||||
|
|
||||||
return repositorymodels.StatusOk
|
return repositorymodels.StatusOk
|
||||||
}
|
}
|
||||||
|
|
||||||
func CreateDocument(databaseId string, collectionId string, document map[string]interface{}) (repositorymodels.Document, repositorymodels.RepositoryStatus) {
|
func (r *DataRepository) CreateDocument(databaseId string, collectionId string, document map[string]interface{}) (repositorymodels.Document, repositorymodels.RepositoryStatus) {
|
||||||
|
r.storeState.Lock()
|
||||||
|
defer r.storeState.Unlock()
|
||||||
|
|
||||||
var ok bool
|
var ok bool
|
||||||
var documentId string
|
var documentId string
|
||||||
var database repositorymodels.Database
|
var database repositorymodels.Database
|
||||||
@@ -70,15 +82,15 @@ func CreateDocument(databaseId string, collectionId string, document map[string]
|
|||||||
document["id"] = documentId
|
document["id"] = documentId
|
||||||
}
|
}
|
||||||
|
|
||||||
if database, ok = storeState.Databases[databaseId]; !ok {
|
if database, ok = r.storeState.Databases[databaseId]; !ok {
|
||||||
return repositorymodels.Document{}, repositorymodels.StatusNotFound
|
return repositorymodels.Document{}, repositorymodels.StatusNotFound
|
||||||
}
|
}
|
||||||
|
|
||||||
if collection, ok = storeState.Collections[databaseId][collectionId]; !ok {
|
if collection, ok = r.storeState.Collections[databaseId][collectionId]; !ok {
|
||||||
return repositorymodels.Document{}, repositorymodels.StatusNotFound
|
return repositorymodels.Document{}, repositorymodels.StatusNotFound
|
||||||
}
|
}
|
||||||
|
|
||||||
if _, ok := storeState.Documents[databaseId][collectionId][documentId]; ok {
|
if _, ok := r.storeState.Documents[databaseId][collectionId][documentId]; ok {
|
||||||
return repositorymodels.Document{}, repositorymodels.Conflict
|
return repositorymodels.Document{}, repositorymodels.Conflict
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -87,19 +99,19 @@ func CreateDocument(databaseId string, collectionId string, document map[string]
|
|||||||
document["_etag"] = fmt.Sprintf("\"%s\"", uuid.New())
|
document["_etag"] = fmt.Sprintf("\"%s\"", uuid.New())
|
||||||
document["_self"] = fmt.Sprintf("dbs/%s/colls/%s/docs/%s/", database.ResourceID, collection.ResourceID, document["_rid"])
|
document["_self"] = fmt.Sprintf("dbs/%s/colls/%s/docs/%s/", database.ResourceID, collection.ResourceID, document["_rid"])
|
||||||
|
|
||||||
storeState.Documents[databaseId][collectionId][documentId] = document
|
r.storeState.Documents[databaseId][collectionId][documentId] = document
|
||||||
|
|
||||||
return document, repositorymodels.StatusOk
|
return document, repositorymodels.StatusOk
|
||||||
}
|
}
|
||||||
|
|
||||||
func ExecuteQueryDocuments(databaseId string, collectionId string, query string, queryParameters map[string]interface{}) ([]memoryexecutor.RowType, repositorymodels.RepositoryStatus) {
|
func (r *DataRepository) ExecuteQueryDocuments(databaseId string, collectionId string, query string, queryParameters map[string]interface{}) ([]memoryexecutor.RowType, repositorymodels.RepositoryStatus) {
|
||||||
parsedQuery, err := nosql.Parse("", []byte(query))
|
parsedQuery, err := nosql.Parse("", []byte(query))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Printf("Failed to parse query: %s\nerr: %v", query, err)
|
log.Printf("Failed to parse query: %s\nerr: %v", query, err)
|
||||||
return nil, repositorymodels.BadRequest
|
return nil, repositorymodels.BadRequest
|
||||||
}
|
}
|
||||||
|
|
||||||
collectionDocuments, status := GetAllDocuments(databaseId, collectionId)
|
collectionDocuments, status := r.GetAllDocuments(databaseId, collectionId)
|
||||||
if status != repositorymodels.StatusOk {
|
if status != repositorymodels.StatusOk {
|
||||||
return nil, status
|
return nil, status
|
||||||
}
|
}
|
||||||
@@ -111,7 +123,7 @@ func ExecuteQueryDocuments(databaseId string, collectionId string, query string,
|
|||||||
|
|
||||||
if typedQuery, ok := parsedQuery.(parsers.SelectStmt); ok {
|
if typedQuery, ok := parsedQuery.(parsers.SelectStmt); ok {
|
||||||
typedQuery.Parameters = queryParameters
|
typedQuery.Parameters = queryParameters
|
||||||
return memoryexecutor.Execute(typedQuery, covDocs), repositorymodels.StatusOk
|
return memoryexecutor.ExecuteQuery(typedQuery, covDocs), repositorymodels.StatusOk
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil, repositorymodels.BadRequest
|
return nil, repositorymodels.BadRequest
|
||||||
|
|||||||
@@ -9,16 +9,19 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
// I have no idea what this is tbh
|
// I have no idea what this is tbh
|
||||||
func GetPartitionKeyRanges(databaseId string, collectionId string) ([]repositorymodels.PartitionKeyRange, repositorymodels.RepositoryStatus) {
|
func (r *DataRepository) GetPartitionKeyRanges(databaseId string, collectionId string) ([]repositorymodels.PartitionKeyRange, repositorymodels.RepositoryStatus) {
|
||||||
|
r.storeState.RLock()
|
||||||
|
defer r.storeState.RUnlock()
|
||||||
|
|
||||||
databaseRid := databaseId
|
databaseRid := databaseId
|
||||||
collectionRid := collectionId
|
collectionRid := collectionId
|
||||||
var timestamp int64 = 0
|
var timestamp int64 = 0
|
||||||
|
|
||||||
if database, ok := storeState.Databases[databaseId]; !ok {
|
if database, ok := r.storeState.Databases[databaseId]; !ok {
|
||||||
databaseRid = database.ResourceID
|
databaseRid = database.ResourceID
|
||||||
}
|
}
|
||||||
|
|
||||||
if collection, ok := storeState.Collections[databaseId][collectionId]; !ok {
|
if collection, ok := r.storeState.Collections[databaseId][collectionId]; !ok {
|
||||||
collectionRid = collection.ResourceID
|
collectionRid = collection.ResourceID
|
||||||
timestamp = collection.TimeStamp
|
timestamp = collection.TimeStamp
|
||||||
}
|
}
|
||||||
|
|||||||
37
internal/repositories/repositories.go
Normal file
37
internal/repositories/repositories.go
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
package repositories
|
||||||
|
|
||||||
|
import repositorymodels "github.com/pikami/cosmium/internal/repository_models"
|
||||||
|
|
||||||
|
type DataRepository struct {
|
||||||
|
storedProcedures []repositorymodels.StoredProcedure
|
||||||
|
triggers []repositorymodels.Trigger
|
||||||
|
userDefinedFunctions []repositorymodels.UserDefinedFunction
|
||||||
|
storeState repositorymodels.State
|
||||||
|
|
||||||
|
initialDataFilePath string
|
||||||
|
persistDataFilePath string
|
||||||
|
}
|
||||||
|
|
||||||
|
type RepositoryOptions struct {
|
||||||
|
InitialDataFilePath string
|
||||||
|
PersistDataFilePath string
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewDataRepository(options RepositoryOptions) *DataRepository {
|
||||||
|
repository := &DataRepository{
|
||||||
|
storedProcedures: []repositorymodels.StoredProcedure{},
|
||||||
|
triggers: []repositorymodels.Trigger{},
|
||||||
|
userDefinedFunctions: []repositorymodels.UserDefinedFunction{},
|
||||||
|
storeState: repositorymodels.State{
|
||||||
|
Databases: make(map[string]repositorymodels.Database),
|
||||||
|
Collections: make(map[string]map[string]repositorymodels.Collection),
|
||||||
|
Documents: make(map[string]map[string]map[string]repositorymodels.Document),
|
||||||
|
},
|
||||||
|
initialDataFilePath: options.InitialDataFilePath,
|
||||||
|
persistDataFilePath: options.PersistDataFilePath,
|
||||||
|
}
|
||||||
|
|
||||||
|
repository.InitializeRepository()
|
||||||
|
|
||||||
|
return repository
|
||||||
|
}
|
||||||
@@ -6,28 +6,18 @@ import (
|
|||||||
"os"
|
"os"
|
||||||
"reflect"
|
"reflect"
|
||||||
|
|
||||||
"github.com/pikami/cosmium/api/config"
|
|
||||||
"github.com/pikami/cosmium/internal/logger"
|
"github.com/pikami/cosmium/internal/logger"
|
||||||
repositorymodels "github.com/pikami/cosmium/internal/repository_models"
|
repositorymodels "github.com/pikami/cosmium/internal/repository_models"
|
||||||
)
|
)
|
||||||
|
|
||||||
var storedProcedures = []repositorymodels.StoredProcedure{}
|
func (r *DataRepository) InitializeRepository() {
|
||||||
var triggers = []repositorymodels.Trigger{}
|
if r.initialDataFilePath != "" {
|
||||||
var userDefinedFunctions = []repositorymodels.UserDefinedFunction{}
|
r.LoadStateFS(r.initialDataFilePath)
|
||||||
var storeState = repositorymodels.State{
|
|
||||||
Databases: make(map[string]repositorymodels.Database),
|
|
||||||
Collections: make(map[string]map[string]repositorymodels.Collection),
|
|
||||||
Documents: make(map[string]map[string]map[string]repositorymodels.Document),
|
|
||||||
}
|
|
||||||
|
|
||||||
func InitializeRepository() {
|
|
||||||
if config.Config.InitialDataFilePath != "" {
|
|
||||||
LoadStateFS(config.Config.InitialDataFilePath)
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if config.Config.PersistDataFilePath != "" {
|
if r.persistDataFilePath != "" {
|
||||||
stat, err := os.Stat(config.Config.PersistDataFilePath)
|
stat, err := os.Stat(r.persistDataFilePath)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -37,36 +27,52 @@ func InitializeRepository() {
|
|||||||
os.Exit(1)
|
os.Exit(1)
|
||||||
}
|
}
|
||||||
|
|
||||||
LoadStateFS(config.Config.PersistDataFilePath)
|
r.LoadStateFS(r.persistDataFilePath)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func LoadStateFS(filePath string) {
|
func (r *DataRepository) LoadStateFS(filePath string) {
|
||||||
data, err := os.ReadFile(filePath)
|
data, err := os.ReadFile(filePath)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatalf("Error reading state JSON file: %v", err)
|
log.Fatalf("Error reading state JSON file: %v", err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
var state repositorymodels.State
|
err = r.LoadStateJSON(string(data))
|
||||||
if err := json.Unmarshal(data, &state); err != nil {
|
if err != nil {
|
||||||
log.Fatalf("Error unmarshalling state JSON: %v", err)
|
log.Fatalf("Error unmarshalling state JSON: %v", err)
|
||||||
return
|
|
||||||
}
|
}
|
||||||
|
|
||||||
logger.Info("Loaded state:")
|
|
||||||
logger.Infof("Databases: %d\n", getLength(state.Databases))
|
|
||||||
logger.Infof("Collections: %d\n", getLength(state.Collections))
|
|
||||||
logger.Infof("Documents: %d\n", getLength(state.Documents))
|
|
||||||
|
|
||||||
storeState = state
|
|
||||||
|
|
||||||
ensureStoreStateNoNullReferences()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func SaveStateFS(filePath string) {
|
func (r *DataRepository) LoadStateJSON(jsonData string) error {
|
||||||
data, err := json.MarshalIndent(storeState, "", "\t")
|
r.storeState.RLock()
|
||||||
|
defer r.storeState.RUnlock()
|
||||||
|
|
||||||
|
var state repositorymodels.State
|
||||||
|
if err := json.Unmarshal([]byte(jsonData), &state); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
r.storeState.Collections = state.Collections
|
||||||
|
r.storeState.Databases = state.Databases
|
||||||
|
r.storeState.Documents = state.Documents
|
||||||
|
|
||||||
|
r.ensureStoreStateNoNullReferences()
|
||||||
|
|
||||||
|
logger.Info("Loaded state:")
|
||||||
|
logger.Infof("Databases: %d\n", getLength(r.storeState.Databases))
|
||||||
|
logger.Infof("Collections: %d\n", getLength(r.storeState.Collections))
|
||||||
|
logger.Infof("Documents: %d\n", getLength(r.storeState.Documents))
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *DataRepository) SaveStateFS(filePath string) {
|
||||||
|
r.storeState.RLock()
|
||||||
|
defer r.storeState.RUnlock()
|
||||||
|
|
||||||
|
data, err := json.MarshalIndent(r.storeState, "", "\t")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
logger.Errorf("Failed to save state: %v\n", err)
|
logger.Errorf("Failed to save state: %v\n", err)
|
||||||
return
|
return
|
||||||
@@ -75,13 +81,22 @@ func SaveStateFS(filePath string) {
|
|||||||
os.WriteFile(filePath, data, os.ModePerm)
|
os.WriteFile(filePath, data, os.ModePerm)
|
||||||
|
|
||||||
logger.Info("Saved state:")
|
logger.Info("Saved state:")
|
||||||
logger.Infof("Databases: %d\n", getLength(storeState.Databases))
|
logger.Infof("Databases: %d\n", getLength(r.storeState.Databases))
|
||||||
logger.Infof("Collections: %d\n", getLength(storeState.Collections))
|
logger.Infof("Collections: %d\n", getLength(r.storeState.Collections))
|
||||||
logger.Infof("Documents: %d\n", getLength(storeState.Documents))
|
logger.Infof("Documents: %d\n", getLength(r.storeState.Documents))
|
||||||
}
|
}
|
||||||
|
|
||||||
func GetState() repositorymodels.State {
|
func (r *DataRepository) GetState() (string, error) {
|
||||||
return storeState
|
r.storeState.RLock()
|
||||||
|
defer r.storeState.RUnlock()
|
||||||
|
|
||||||
|
data, err := json.MarshalIndent(r.storeState, "", "\t")
|
||||||
|
if err != nil {
|
||||||
|
logger.Errorf("Failed to serialize state: %v\n", err)
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
return string(data), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func getLength(v interface{}) int {
|
func getLength(v interface{}) int {
|
||||||
@@ -109,36 +124,36 @@ func getLength(v interface{}) int {
|
|||||||
return count
|
return count
|
||||||
}
|
}
|
||||||
|
|
||||||
func ensureStoreStateNoNullReferences() {
|
func (r *DataRepository) ensureStoreStateNoNullReferences() {
|
||||||
if storeState.Databases == nil {
|
if r.storeState.Databases == nil {
|
||||||
storeState.Databases = make(map[string]repositorymodels.Database)
|
r.storeState.Databases = make(map[string]repositorymodels.Database)
|
||||||
}
|
}
|
||||||
|
|
||||||
if storeState.Collections == nil {
|
if r.storeState.Collections == nil {
|
||||||
storeState.Collections = make(map[string]map[string]repositorymodels.Collection)
|
r.storeState.Collections = make(map[string]map[string]repositorymodels.Collection)
|
||||||
}
|
}
|
||||||
|
|
||||||
if storeState.Documents == nil {
|
if r.storeState.Documents == nil {
|
||||||
storeState.Documents = make(map[string]map[string]map[string]repositorymodels.Document)
|
r.storeState.Documents = make(map[string]map[string]map[string]repositorymodels.Document)
|
||||||
}
|
}
|
||||||
|
|
||||||
for database := range storeState.Databases {
|
for database := range r.storeState.Databases {
|
||||||
if storeState.Collections[database] == nil {
|
if r.storeState.Collections[database] == nil {
|
||||||
storeState.Collections[database] = make(map[string]repositorymodels.Collection)
|
r.storeState.Collections[database] = make(map[string]repositorymodels.Collection)
|
||||||
}
|
}
|
||||||
|
|
||||||
if storeState.Documents[database] == nil {
|
if r.storeState.Documents[database] == nil {
|
||||||
storeState.Documents[database] = make(map[string]map[string]repositorymodels.Document)
|
r.storeState.Documents[database] = make(map[string]map[string]repositorymodels.Document)
|
||||||
}
|
}
|
||||||
|
|
||||||
for collection := range storeState.Collections[database] {
|
for collection := range r.storeState.Collections[database] {
|
||||||
if storeState.Documents[database][collection] == nil {
|
if r.storeState.Documents[database][collection] == nil {
|
||||||
storeState.Documents[database][collection] = make(map[string]repositorymodels.Document)
|
r.storeState.Documents[database][collection] = make(map[string]repositorymodels.Document)
|
||||||
}
|
}
|
||||||
|
|
||||||
for document := range storeState.Documents[database][collection] {
|
for document := range r.storeState.Documents[database][collection] {
|
||||||
if storeState.Documents[database][collection][document] == nil {
|
if r.storeState.Documents[database][collection][document] == nil {
|
||||||
delete(storeState.Documents[database][collection], document)
|
delete(r.storeState.Documents[database][collection], document)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,6 +2,6 @@ package repositories
|
|||||||
|
|
||||||
import repositorymodels "github.com/pikami/cosmium/internal/repository_models"
|
import repositorymodels "github.com/pikami/cosmium/internal/repository_models"
|
||||||
|
|
||||||
func GetAllStoredProcedures(databaseId string, collectionId string) ([]repositorymodels.StoredProcedure, repositorymodels.RepositoryStatus) {
|
func (r *DataRepository) GetAllStoredProcedures(databaseId string, collectionId string) ([]repositorymodels.StoredProcedure, repositorymodels.RepositoryStatus) {
|
||||||
return storedProcedures, repositorymodels.StatusOk
|
return r.storedProcedures, repositorymodels.StatusOk
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,6 +2,6 @@ package repositories
|
|||||||
|
|
||||||
import repositorymodels "github.com/pikami/cosmium/internal/repository_models"
|
import repositorymodels "github.com/pikami/cosmium/internal/repository_models"
|
||||||
|
|
||||||
func GetAllTriggers(databaseId string, collectionId string) ([]repositorymodels.Trigger, repositorymodels.RepositoryStatus) {
|
func (r *DataRepository) GetAllTriggers(databaseId string, collectionId string) ([]repositorymodels.Trigger, repositorymodels.RepositoryStatus) {
|
||||||
return triggers, repositorymodels.StatusOk
|
return r.triggers, repositorymodels.StatusOk
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,6 +2,6 @@ package repositories
|
|||||||
|
|
||||||
import repositorymodels "github.com/pikami/cosmium/internal/repository_models"
|
import repositorymodels "github.com/pikami/cosmium/internal/repository_models"
|
||||||
|
|
||||||
func GetAllUserDefinedFunctions(databaseId string, collectionId string) ([]repositorymodels.UserDefinedFunction, repositorymodels.RepositoryStatus) {
|
func (r *DataRepository) GetAllUserDefinedFunctions(databaseId string, collectionId string) ([]repositorymodels.UserDefinedFunction, repositorymodels.RepositoryStatus) {
|
||||||
return userDefinedFunctions, repositorymodels.StatusOk
|
return r.userDefinedFunctions, repositorymodels.StatusOk
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
package repositorymodels
|
package repositorymodels
|
||||||
|
|
||||||
|
import "sync"
|
||||||
|
|
||||||
type Database struct {
|
type Database struct {
|
||||||
ID string `json:"id"`
|
ID string `json:"id"`
|
||||||
TimeStamp int64 `json:"_ts"`
|
TimeStamp int64 `json:"_ts"`
|
||||||
@@ -101,6 +103,8 @@ type PartitionKeyRange struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type State struct {
|
type State struct {
|
||||||
|
sync.RWMutex
|
||||||
|
|
||||||
// Map databaseId -> Database
|
// Map databaseId -> Database
|
||||||
Databases map[string]Database `json:"databases"`
|
Databases map[string]Database `json:"databases"`
|
||||||
|
|
||||||
|
|||||||
33
main.go
33
main.go
@@ -1,33 +0,0 @@
|
|||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"os"
|
|
||||||
"os/signal"
|
|
||||||
"syscall"
|
|
||||||
|
|
||||||
"github.com/pikami/cosmium/api"
|
|
||||||
"github.com/pikami/cosmium/api/config"
|
|
||||||
"github.com/pikami/cosmium/internal/repositories"
|
|
||||||
)
|
|
||||||
|
|
||||||
func main() {
|
|
||||||
config.ParseFlags()
|
|
||||||
|
|
||||||
repositories.InitializeRepository()
|
|
||||||
|
|
||||||
go api.StartAPI()
|
|
||||||
|
|
||||||
waitForExit()
|
|
||||||
}
|
|
||||||
|
|
||||||
func waitForExit() {
|
|
||||||
sigs := make(chan os.Signal, 1)
|
|
||||||
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
|
|
||||||
|
|
||||||
// Block until a exit signal is received
|
|
||||||
<-sigs
|
|
||||||
|
|
||||||
if config.Config.PersistDataFilePath != "" {
|
|
||||||
repositories.SaveStateFS(config.Config.PersistDataFilePath)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -5,6 +5,7 @@ type SelectStmt struct {
|
|||||||
Table Table
|
Table Table
|
||||||
JoinItems []JoinItem
|
JoinItems []JoinItem
|
||||||
Filters interface{}
|
Filters interface{}
|
||||||
|
Exists bool
|
||||||
Distinct bool
|
Distinct bool
|
||||||
Count int
|
Count int
|
||||||
Offset int
|
Offset int
|
||||||
@@ -14,7 +15,8 @@ type SelectStmt struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type Table struct {
|
type Table struct {
|
||||||
Value string
|
Value string
|
||||||
|
SelectItem SelectItem
|
||||||
}
|
}
|
||||||
|
|
||||||
type JoinItem struct {
|
type JoinItem struct {
|
||||||
@@ -30,6 +32,7 @@ const (
|
|||||||
SelectItemTypeArray
|
SelectItemTypeArray
|
||||||
SelectItemTypeConstant
|
SelectItemTypeConstant
|
||||||
SelectItemTypeFunctionCall
|
SelectItemTypeFunctionCall
|
||||||
|
SelectItemTypeSubQuery
|
||||||
)
|
)
|
||||||
|
|
||||||
type SelectItem struct {
|
type SelectItem struct {
|
||||||
|
|||||||
@@ -122,4 +122,25 @@ func Test_Parse(t *testing.T) {
|
|||||||
},
|
},
|
||||||
)
|
)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
t.Run("Should parse IN selector", func(t *testing.T) {
|
||||||
|
testQueryParse(
|
||||||
|
t,
|
||||||
|
`SELECT c.id FROM c IN c.tags`,
|
||||||
|
parsers.SelectStmt{
|
||||||
|
SelectItems: []parsers.SelectItem{
|
||||||
|
{
|
||||||
|
Path: []string{"c", "id"},
|
||||||
|
Type: parsers.SelectItemTypeField,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
Table: parsers.Table{
|
||||||
|
Value: "c",
|
||||||
|
SelectItem: parsers.SelectItem{
|
||||||
|
Path: []string{"c", "tags"},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
)
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -4,16 +4,19 @@ package nosql
|
|||||||
import "github.com/pikami/cosmium/parsers"
|
import "github.com/pikami/cosmium/parsers"
|
||||||
|
|
||||||
func makeSelectStmt(
|
func makeSelectStmt(
|
||||||
columns, table, joinItems,
|
columns, fromClause, joinItems,
|
||||||
whereClause interface{}, distinctClause interface{},
|
whereClause interface{}, distinctClause interface{},
|
||||||
count interface{}, groupByClause interface{}, orderList interface{},
|
count interface{}, groupByClause interface{}, orderList interface{},
|
||||||
offsetClause interface{},
|
offsetClause interface{},
|
||||||
) (parsers.SelectStmt, error) {
|
) (parsers.SelectStmt, error) {
|
||||||
selectStmt := parsers.SelectStmt{
|
selectStmt := parsers.SelectStmt{
|
||||||
SelectItems: columns.([]parsers.SelectItem),
|
SelectItems: columns.([]parsers.SelectItem),
|
||||||
Table: table.(parsers.Table),
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if fromTable, ok := fromClause.(parsers.Table); ok {
|
||||||
|
selectStmt.Table = fromTable
|
||||||
|
}
|
||||||
|
|
||||||
if joinItemsArray, ok := joinItems.([]interface{}); ok && len(joinItemsArray) > 0 {
|
if joinItemsArray, ok := joinItems.([]interface{}); ok && len(joinItemsArray) > 0 {
|
||||||
selectStmt.JoinItems = make([]parsers.JoinItem, len(joinItemsArray))
|
selectStmt.JoinItems = make([]parsers.JoinItem, len(joinItemsArray))
|
||||||
for i, joinItem := range joinItemsArray {
|
for i, joinItem := range joinItemsArray {
|
||||||
@@ -56,10 +59,18 @@ func makeSelectStmt(
|
|||||||
}
|
}
|
||||||
|
|
||||||
func makeJoin(table interface{}, column interface{}) (parsers.JoinItem, error) {
|
func makeJoin(table interface{}, column interface{}) (parsers.JoinItem, error) {
|
||||||
return parsers.JoinItem{
|
joinItem := parsers.JoinItem{}
|
||||||
Table: table.(parsers.Table),
|
|
||||||
SelectItem: column.(parsers.SelectItem),
|
if selectItem, isSelectItem := column.(parsers.SelectItem); isSelectItem {
|
||||||
}, nil
|
joinItem.SelectItem = selectItem
|
||||||
|
joinItem.Table.Value = selectItem.Alias
|
||||||
|
}
|
||||||
|
|
||||||
|
if tableTyped, isTable := table.(parsers.Table); isTable {
|
||||||
|
joinItem.Table = tableTyped
|
||||||
|
}
|
||||||
|
|
||||||
|
return joinItem, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func makeSelectItem(name interface{}, path interface{}, selectItemType parsers.SelectItemType) (parsers.SelectItem, error) {
|
func makeSelectItem(name interface{}, path interface{}, selectItemType parsers.SelectItemType) (parsers.SelectItem, error) {
|
||||||
@@ -177,13 +188,13 @@ SelectStmt <- Select ws
|
|||||||
distinctClause:DistinctClause? ws
|
distinctClause:DistinctClause? ws
|
||||||
topClause:TopClause? ws
|
topClause:TopClause? ws
|
||||||
columns:Selection ws
|
columns:Selection ws
|
||||||
From ws table:TableName ws
|
fromClause:FromClause? ws
|
||||||
joinClauses:JoinClause* ws
|
joinClauses:(ws join:JoinClause { return join, nil })* ws
|
||||||
whereClause:(ws Where ws condition:Condition { return condition, nil })?
|
whereClause:(ws Where ws condition:Condition { return condition, nil })?
|
||||||
groupByClause:(ws GroupBy ws columns:ColumnList { return columns, nil })?
|
groupByClause:(ws GroupBy ws columns:ColumnList { return columns, nil })?
|
||||||
orderByClause:OrderByClause?
|
orderByClause:(ws order:OrderByClause { return order, nil })?
|
||||||
offsetClause:OffsetClause? {
|
offsetClause:(ws offset:OffsetClause { return offset, nil })? {
|
||||||
return makeSelectStmt(columns, table, joinClauses, whereClause,
|
return makeSelectStmt(columns, fromClause, joinClauses, whereClause,
|
||||||
distinctClause, topClause, groupByClause, orderByClause, offsetClause)
|
distinctClause, topClause, groupByClause, orderByClause, offsetClause)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -193,8 +204,49 @@ TopClause <- Top ws count:Integer {
|
|||||||
return count, nil
|
return count, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
FromClause <- From ws table:TableName selectItem:(ws "IN"i ws column:SelectItem { return column, nil })? {
|
||||||
|
tableTyped := table.(parsers.Table)
|
||||||
|
|
||||||
|
if selectItem != nil {
|
||||||
|
tableTyped.SelectItem = selectItem.(parsers.SelectItem)
|
||||||
|
}
|
||||||
|
|
||||||
|
return tableTyped, nil
|
||||||
|
} / From ws subQuery:SubQuerySelectItem {
|
||||||
|
subQueryTyped := subQuery.(parsers.SelectItem)
|
||||||
|
table := parsers.Table{
|
||||||
|
Value: subQueryTyped.Alias,
|
||||||
|
SelectItem: subQueryTyped,
|
||||||
|
}
|
||||||
|
return table, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
SubQuery <- exists:(exists:Exists ws { return exists, nil })? "(" ws selectStmt:SelectStmt ws ")" {
|
||||||
|
if selectStatement, isGoodValue := selectStmt.(parsers.SelectStmt); isGoodValue {
|
||||||
|
selectStatement.Exists = exists != nil
|
||||||
|
return selectStatement, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
return selectStmt, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
SubQuerySelectItem <- subQuery:SubQuery asClause:(ws alias:AsClause { return alias, nil })? {
|
||||||
|
selectItem := parsers.SelectItem{
|
||||||
|
Type: parsers.SelectItemTypeSubQuery,
|
||||||
|
Value: subQuery,
|
||||||
|
}
|
||||||
|
|
||||||
|
if tableName, isString := asClause.(string); isString {
|
||||||
|
selectItem.Alias = tableName
|
||||||
|
}
|
||||||
|
|
||||||
|
return selectItem, nil
|
||||||
|
}
|
||||||
|
|
||||||
JoinClause <- Join ws table:TableName ws "IN"i ws column:SelectItem {
|
JoinClause <- Join ws table:TableName ws "IN"i ws column:SelectItem {
|
||||||
return makeJoin(table, column)
|
return makeJoin(table, column)
|
||||||
|
} / Join ws subQuery:SubQuerySelectItem {
|
||||||
|
return makeJoin(nil, subQuery)
|
||||||
}
|
}
|
||||||
|
|
||||||
OffsetClause <- "OFFSET"i ws offset:IntegerLiteral ws "LIMIT"i ws limit:IntegerLiteral {
|
OffsetClause <- "OFFSET"i ws offset:IntegerLiteral ws "LIMIT"i ws limit:IntegerLiteral {
|
||||||
@@ -241,7 +293,7 @@ SelectProperty <- name:Identifier path:(DotFieldAccess / ArrayFieldAccess)* {
|
|||||||
return makeSelectItem(name, path, parsers.SelectItemTypeField)
|
return makeSelectItem(name, path, parsers.SelectItemTypeField)
|
||||||
}
|
}
|
||||||
|
|
||||||
SelectItem <- selectItem:(Literal / FunctionCall / SelectArray / SelectObject / SelectProperty) asClause:AsClause? {
|
SelectItem <- selectItem:(SubQuerySelectItem / Literal / FunctionCall / SelectArray / SelectObject / SelectProperty) asClause:AsClause? {
|
||||||
var itemResult parsers.SelectItem
|
var itemResult parsers.SelectItem
|
||||||
switch typedValue := selectItem.(type) {
|
switch typedValue := selectItem.(type) {
|
||||||
case parsers.SelectItem:
|
case parsers.SelectItem:
|
||||||
@@ -273,6 +325,7 @@ DotFieldAccess <- "." id:Identifier {
|
|||||||
|
|
||||||
ArrayFieldAccess <- "[\"" id:Identifier "\"]" { return id, nil }
|
ArrayFieldAccess <- "[\"" id:Identifier "\"]" { return id, nil }
|
||||||
/ "[" id:Integer "]" { return strconv.Itoa(id.(int)), nil }
|
/ "[" id:Integer "]" { return strconv.Itoa(id.(int)), nil }
|
||||||
|
/ "[" id:ParameterConstant "]" { return id.(parsers.Constant).Value.(string), nil }
|
||||||
|
|
||||||
Identifier <- [a-zA-Z_][a-zA-Z0-9_]* {
|
Identifier <- [a-zA-Z_][a-zA-Z0-9_]* {
|
||||||
return string(c.text), nil
|
return string(c.text), nil
|
||||||
@@ -322,11 +375,13 @@ From <- "FROM"i
|
|||||||
|
|
||||||
Join <- "JOIN"i
|
Join <- "JOIN"i
|
||||||
|
|
||||||
|
Exists <- "EXISTS"i
|
||||||
|
|
||||||
Where <- "WHERE"i
|
Where <- "WHERE"i
|
||||||
|
|
||||||
And <- "AND"i
|
And <- "AND"i
|
||||||
|
|
||||||
Or <- "OR"i
|
Or <- "OR"i wss
|
||||||
|
|
||||||
GroupBy <- "GROUP"i ws "BY"i
|
GroupBy <- "GROUP"i ws "BY"i
|
||||||
|
|
||||||
@@ -677,4 +732,6 @@ non_escape_character <- !(escape_character) char:.
|
|||||||
|
|
||||||
ws <- [ \t\n\r]*
|
ws <- [ \t\n\r]*
|
||||||
|
|
||||||
|
wss <- [ \t\n\r]+
|
||||||
|
|
||||||
EOF <- !.
|
EOF <- !.
|
||||||
|
|||||||
@@ -22,6 +22,20 @@ func Test_Parse_Select(t *testing.T) {
|
|||||||
)
|
)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
t.Run("Should parse SELECT with query parameters as accessor", func(t *testing.T) {
|
||||||
|
testQueryParse(
|
||||||
|
t,
|
||||||
|
`SELECT c.id, c[@param] FROM c`,
|
||||||
|
parsers.SelectStmt{
|
||||||
|
SelectItems: []parsers.SelectItem{
|
||||||
|
{Path: []string{"c", "id"}},
|
||||||
|
{Path: []string{"c", "@param"}},
|
||||||
|
},
|
||||||
|
Table: parsers.Table{Value: "c"},
|
||||||
|
},
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
t.Run("Should parse SELECT DISTINCT", func(t *testing.T) {
|
t.Run("Should parse SELECT DISTINCT", func(t *testing.T) {
|
||||||
testQueryParse(
|
testQueryParse(
|
||||||
t,
|
t,
|
||||||
|
|||||||
125
parsers/nosql/subquery_test.go
Normal file
125
parsers/nosql/subquery_test.go
Normal file
@@ -0,0 +1,125 @@
|
|||||||
|
package nosql_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/pikami/cosmium/parsers"
|
||||||
|
)
|
||||||
|
|
||||||
|
func Test_Parse_SubQuery(t *testing.T) {
|
||||||
|
|
||||||
|
t.Run("Should parse FROM subquery", func(t *testing.T) {
|
||||||
|
testQueryParse(
|
||||||
|
t,
|
||||||
|
`SELECT c.id FROM (SELECT VALUE cc["info"] FROM cc) AS c`,
|
||||||
|
parsers.SelectStmt{
|
||||||
|
SelectItems: []parsers.SelectItem{
|
||||||
|
{Path: []string{"c", "id"}},
|
||||||
|
},
|
||||||
|
Table: parsers.Table{
|
||||||
|
Value: "c",
|
||||||
|
SelectItem: parsers.SelectItem{
|
||||||
|
Alias: "c",
|
||||||
|
Type: parsers.SelectItemTypeSubQuery,
|
||||||
|
Value: parsers.SelectStmt{
|
||||||
|
Table: parsers.Table{Value: "cc"},
|
||||||
|
SelectItems: []parsers.SelectItem{
|
||||||
|
{Path: []string{"cc", "info"}, IsTopLevel: true},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("Should parse JOIN subquery", func(t *testing.T) {
|
||||||
|
testQueryParse(
|
||||||
|
t,
|
||||||
|
`SELECT c.id, cc.name FROM c JOIN (SELECT tag.name FROM tag IN c.tags) AS cc`,
|
||||||
|
parsers.SelectStmt{
|
||||||
|
SelectItems: []parsers.SelectItem{
|
||||||
|
{Path: []string{"c", "id"}},
|
||||||
|
{Path: []string{"cc", "name"}},
|
||||||
|
},
|
||||||
|
Table: parsers.Table{
|
||||||
|
Value: "c",
|
||||||
|
},
|
||||||
|
JoinItems: []parsers.JoinItem{
|
||||||
|
{
|
||||||
|
Table: parsers.Table{
|
||||||
|
Value: "cc",
|
||||||
|
},
|
||||||
|
SelectItem: parsers.SelectItem{
|
||||||
|
Alias: "cc",
|
||||||
|
Type: parsers.SelectItemTypeSubQuery,
|
||||||
|
Value: parsers.SelectStmt{
|
||||||
|
SelectItems: []parsers.SelectItem{
|
||||||
|
{Path: []string{"tag", "name"}},
|
||||||
|
},
|
||||||
|
Table: parsers.Table{
|
||||||
|
Value: "tag",
|
||||||
|
SelectItem: parsers.SelectItem{
|
||||||
|
Path: []string{"c", "tags"},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("Should parse JOIN EXISTS subquery", func(t *testing.T) {
|
||||||
|
testQueryParse(
|
||||||
|
t,
|
||||||
|
`SELECT c.id
|
||||||
|
FROM c
|
||||||
|
JOIN (
|
||||||
|
SELECT VALUE EXISTS(SELECT tag.name FROM tag IN c.tags)
|
||||||
|
) AS hasTags
|
||||||
|
WHERE hasTags`,
|
||||||
|
parsers.SelectStmt{
|
||||||
|
SelectItems: []parsers.SelectItem{
|
||||||
|
{Path: []string{"c", "id"}},
|
||||||
|
},
|
||||||
|
Table: parsers.Table{
|
||||||
|
Value: "c",
|
||||||
|
},
|
||||||
|
JoinItems: []parsers.JoinItem{
|
||||||
|
{
|
||||||
|
Table: parsers.Table{Value: "hasTags"},
|
||||||
|
SelectItem: parsers.SelectItem{
|
||||||
|
Alias: "hasTags",
|
||||||
|
Type: parsers.SelectItemTypeSubQuery,
|
||||||
|
Value: parsers.SelectStmt{
|
||||||
|
SelectItems: []parsers.SelectItem{
|
||||||
|
{
|
||||||
|
IsTopLevel: true,
|
||||||
|
Type: parsers.SelectItemTypeSubQuery,
|
||||||
|
Value: parsers.SelectStmt{
|
||||||
|
SelectItems: []parsers.SelectItem{
|
||||||
|
{Path: []string{"tag", "name"}},
|
||||||
|
},
|
||||||
|
Table: parsers.Table{
|
||||||
|
Value: "tag",
|
||||||
|
SelectItem: parsers.SelectItem{
|
||||||
|
Path: []string{"c", "tags"},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
Exists: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
Filters: parsers.SelectItem{
|
||||||
|
Path: []string{"hasTags"},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
)
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -6,21 +6,19 @@ import (
|
|||||||
"github.com/pikami/cosmium/parsers"
|
"github.com/pikami/cosmium/parsers"
|
||||||
)
|
)
|
||||||
|
|
||||||
func (c memoryExecutorContext) aggregate_Avg(arguments []interface{}, row RowType) interface{} {
|
func (r rowContext) aggregate_Avg(arguments []interface{}) interface{} {
|
||||||
selectExpression := arguments[0].(parsers.SelectItem)
|
selectExpression := arguments[0].(parsers.SelectItem)
|
||||||
sum := 0.0
|
sum := 0.0
|
||||||
count := 0
|
count := 0
|
||||||
|
|
||||||
if array, isArray := row.([]RowWithJoins); isArray {
|
for _, item := range r.grouppedRows {
|
||||||
for _, item := range array {
|
value := item.resolveSelectItem(selectExpression)
|
||||||
value := c.getFieldValue(selectExpression, item)
|
if numericValue, ok := value.(float64); ok {
|
||||||
if numericValue, ok := value.(float64); ok {
|
sum += numericValue
|
||||||
sum += numericValue
|
count++
|
||||||
count++
|
} else if numericValue, ok := value.(int); ok {
|
||||||
} else if numericValue, ok := value.(int); ok {
|
sum += float64(numericValue)
|
||||||
sum += float64(numericValue)
|
count++
|
||||||
count++
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -31,41 +29,37 @@ func (c memoryExecutorContext) aggregate_Avg(arguments []interface{}, row RowTyp
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c memoryExecutorContext) aggregate_Count(arguments []interface{}, row RowType) interface{} {
|
func (r rowContext) aggregate_Count(arguments []interface{}) interface{} {
|
||||||
selectExpression := arguments[0].(parsers.SelectItem)
|
selectExpression := arguments[0].(parsers.SelectItem)
|
||||||
count := 0
|
count := 0
|
||||||
|
|
||||||
if array, isArray := row.([]RowWithJoins); isArray {
|
for _, item := range r.grouppedRows {
|
||||||
for _, item := range array {
|
value := item.resolveSelectItem(selectExpression)
|
||||||
value := c.getFieldValue(selectExpression, item)
|
if value != nil {
|
||||||
if value != nil {
|
count++
|
||||||
count++
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return count
|
return count
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c memoryExecutorContext) aggregate_Max(arguments []interface{}, row RowType) interface{} {
|
func (r rowContext) aggregate_Max(arguments []interface{}) interface{} {
|
||||||
selectExpression := arguments[0].(parsers.SelectItem)
|
selectExpression := arguments[0].(parsers.SelectItem)
|
||||||
max := 0.0
|
max := 0.0
|
||||||
count := 0
|
count := 0
|
||||||
|
|
||||||
if array, isArray := row.([]RowWithJoins); isArray {
|
for _, item := range r.grouppedRows {
|
||||||
for _, item := range array {
|
value := item.resolveSelectItem(selectExpression)
|
||||||
value := c.getFieldValue(selectExpression, item)
|
if numericValue, ok := value.(float64); ok {
|
||||||
if numericValue, ok := value.(float64); ok {
|
if numericValue > max {
|
||||||
if numericValue > max {
|
max = numericValue
|
||||||
max = numericValue
|
|
||||||
}
|
|
||||||
count++
|
|
||||||
} else if numericValue, ok := value.(int); ok {
|
|
||||||
if float64(numericValue) > max {
|
|
||||||
max = float64(numericValue)
|
|
||||||
}
|
|
||||||
count++
|
|
||||||
}
|
}
|
||||||
|
count++
|
||||||
|
} else if numericValue, ok := value.(int); ok {
|
||||||
|
if float64(numericValue) > max {
|
||||||
|
max = float64(numericValue)
|
||||||
|
}
|
||||||
|
count++
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -76,25 +70,23 @@ func (c memoryExecutorContext) aggregate_Max(arguments []interface{}, row RowTyp
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c memoryExecutorContext) aggregate_Min(arguments []interface{}, row RowType) interface{} {
|
func (r rowContext) aggregate_Min(arguments []interface{}) interface{} {
|
||||||
selectExpression := arguments[0].(parsers.SelectItem)
|
selectExpression := arguments[0].(parsers.SelectItem)
|
||||||
min := math.MaxFloat64
|
min := math.MaxFloat64
|
||||||
count := 0
|
count := 0
|
||||||
|
|
||||||
if array, isArray := row.([]RowWithJoins); isArray {
|
for _, item := range r.grouppedRows {
|
||||||
for _, item := range array {
|
value := item.resolveSelectItem(selectExpression)
|
||||||
value := c.getFieldValue(selectExpression, item)
|
if numericValue, ok := value.(float64); ok {
|
||||||
if numericValue, ok := value.(float64); ok {
|
if numericValue < min {
|
||||||
if numericValue < min {
|
min = numericValue
|
||||||
min = numericValue
|
|
||||||
}
|
|
||||||
count++
|
|
||||||
} else if numericValue, ok := value.(int); ok {
|
|
||||||
if float64(numericValue) < min {
|
|
||||||
min = float64(numericValue)
|
|
||||||
}
|
|
||||||
count++
|
|
||||||
}
|
}
|
||||||
|
count++
|
||||||
|
} else if numericValue, ok := value.(int); ok {
|
||||||
|
if float64(numericValue) < min {
|
||||||
|
min = float64(numericValue)
|
||||||
|
}
|
||||||
|
count++
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -105,21 +97,19 @@ func (c memoryExecutorContext) aggregate_Min(arguments []interface{}, row RowTyp
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c memoryExecutorContext) aggregate_Sum(arguments []interface{}, row RowType) interface{} {
|
func (r rowContext) aggregate_Sum(arguments []interface{}) interface{} {
|
||||||
selectExpression := arguments[0].(parsers.SelectItem)
|
selectExpression := arguments[0].(parsers.SelectItem)
|
||||||
sum := 0.0
|
sum := 0.0
|
||||||
count := 0
|
count := 0
|
||||||
|
|
||||||
if array, isArray := row.([]RowWithJoins); isArray {
|
for _, item := range r.grouppedRows {
|
||||||
for _, item := range array {
|
value := item.resolveSelectItem(selectExpression)
|
||||||
value := c.getFieldValue(selectExpression, item)
|
if numericValue, ok := value.(float64); ok {
|
||||||
if numericValue, ok := value.(float64); ok {
|
sum += numericValue
|
||||||
sum += numericValue
|
count++
|
||||||
count++
|
} else if numericValue, ok := value.(int); ok {
|
||||||
} else if numericValue, ok := value.(int); ok {
|
sum += float64(numericValue)
|
||||||
sum += float64(numericValue)
|
count++
|
||||||
count++
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -7,17 +7,17 @@ import (
|
|||||||
"github.com/pikami/cosmium/parsers"
|
"github.com/pikami/cosmium/parsers"
|
||||||
)
|
)
|
||||||
|
|
||||||
func (c memoryExecutorContext) array_Concat(arguments []interface{}, row RowType) []interface{} {
|
func (r rowContext) array_Concat(arguments []interface{}) []interface{} {
|
||||||
var result []interface{}
|
var result []interface{}
|
||||||
for _, arg := range arguments {
|
for _, arg := range arguments {
|
||||||
array := c.parseArray(arg, row)
|
array := r.parseArray(arg)
|
||||||
result = append(result, array...)
|
result = append(result, array...)
|
||||||
}
|
}
|
||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c memoryExecutorContext) array_Length(arguments []interface{}, row RowType) int {
|
func (r rowContext) array_Length(arguments []interface{}) int {
|
||||||
array := c.parseArray(arguments[0], row)
|
array := r.parseArray(arguments[0])
|
||||||
if array == nil {
|
if array == nil {
|
||||||
return 0
|
return 0
|
||||||
}
|
}
|
||||||
@@ -25,15 +25,15 @@ func (c memoryExecutorContext) array_Length(arguments []interface{}, row RowType
|
|||||||
return len(array)
|
return len(array)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c memoryExecutorContext) array_Slice(arguments []interface{}, row RowType) []interface{} {
|
func (r rowContext) array_Slice(arguments []interface{}) []interface{} {
|
||||||
var ok bool
|
var ok bool
|
||||||
var start int
|
var start int
|
||||||
var length int
|
var length int
|
||||||
array := c.parseArray(arguments[0], row)
|
array := r.parseArray(arguments[0])
|
||||||
startEx := c.getFieldValue(arguments[1].(parsers.SelectItem), row)
|
startEx := r.resolveSelectItem(arguments[1].(parsers.SelectItem))
|
||||||
|
|
||||||
if arguments[2] != nil {
|
if arguments[2] != nil {
|
||||||
lengthEx := c.getFieldValue(arguments[2].(parsers.SelectItem), row)
|
lengthEx := r.resolveSelectItem(arguments[2].(parsers.SelectItem))
|
||||||
|
|
||||||
if length, ok = lengthEx.(int); !ok {
|
if length, ok = lengthEx.(int); !ok {
|
||||||
logger.Error("array_Slice - got length parameters of wrong type")
|
logger.Error("array_Slice - got length parameters of wrong type")
|
||||||
@@ -65,9 +65,9 @@ func (c memoryExecutorContext) array_Slice(arguments []interface{}, row RowType)
|
|||||||
return array[start:end]
|
return array[start:end]
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c memoryExecutorContext) set_Intersect(arguments []interface{}, row RowType) []interface{} {
|
func (r rowContext) set_Intersect(arguments []interface{}) []interface{} {
|
||||||
set1 := c.parseArray(arguments[0], row)
|
set1 := r.parseArray(arguments[0])
|
||||||
set2 := c.parseArray(arguments[1], row)
|
set2 := r.parseArray(arguments[1])
|
||||||
|
|
||||||
intersection := make(map[interface{}]struct{})
|
intersection := make(map[interface{}]struct{})
|
||||||
if set1 == nil || set2 == nil {
|
if set1 == nil || set2 == nil {
|
||||||
@@ -88,9 +88,9 @@ func (c memoryExecutorContext) set_Intersect(arguments []interface{}, row RowTyp
|
|||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c memoryExecutorContext) set_Union(arguments []interface{}, row RowType) []interface{} {
|
func (r rowContext) set_Union(arguments []interface{}) []interface{} {
|
||||||
set1 := c.parseArray(arguments[0], row)
|
set1 := r.parseArray(arguments[0])
|
||||||
set2 := c.parseArray(arguments[1], row)
|
set2 := r.parseArray(arguments[1])
|
||||||
|
|
||||||
var result []interface{}
|
var result []interface{}
|
||||||
union := make(map[interface{}]struct{})
|
union := make(map[interface{}]struct{})
|
||||||
@@ -111,9 +111,9 @@ func (c memoryExecutorContext) set_Union(arguments []interface{}, row RowType) [
|
|||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c memoryExecutorContext) parseArray(argument interface{}, row RowType) []interface{} {
|
func (r rowContext) parseArray(argument interface{}) []interface{} {
|
||||||
exItem := argument.(parsers.SelectItem)
|
exItem := argument.(parsers.SelectItem)
|
||||||
ex := c.getFieldValue(exItem, row)
|
ex := r.resolveSelectItem(exItem)
|
||||||
|
|
||||||
arrValue := reflect.ValueOf(ex)
|
arrValue := reflect.ValueOf(ex)
|
||||||
if arrValue.Kind() != reflect.Slice {
|
if arrValue.Kind() != reflect.Slice {
|
||||||
|
|||||||
@@ -8,9 +8,9 @@ import (
|
|||||||
"github.com/pikami/cosmium/parsers"
|
"github.com/pikami/cosmium/parsers"
|
||||||
)
|
)
|
||||||
|
|
||||||
func (c memoryExecutorContext) math_Abs(arguments []interface{}, row RowType) interface{} {
|
func (r rowContext) math_Abs(arguments []interface{}) interface{} {
|
||||||
exItem := arguments[0].(parsers.SelectItem)
|
exItem := arguments[0].(parsers.SelectItem)
|
||||||
ex := c.getFieldValue(exItem, row)
|
ex := r.resolveSelectItem(exItem)
|
||||||
|
|
||||||
switch val := ex.(type) {
|
switch val := ex.(type) {
|
||||||
case float64:
|
case float64:
|
||||||
@@ -26,9 +26,9 @@ func (c memoryExecutorContext) math_Abs(arguments []interface{}, row RowType) in
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c memoryExecutorContext) math_Acos(arguments []interface{}, row RowType) interface{} {
|
func (r rowContext) math_Acos(arguments []interface{}) interface{} {
|
||||||
exItem := arguments[0].(parsers.SelectItem)
|
exItem := arguments[0].(parsers.SelectItem)
|
||||||
ex := c.getFieldValue(exItem, row)
|
ex := r.resolveSelectItem(exItem)
|
||||||
|
|
||||||
val, valIsNumber := numToFloat64(ex)
|
val, valIsNumber := numToFloat64(ex)
|
||||||
if !valIsNumber {
|
if !valIsNumber {
|
||||||
@@ -44,9 +44,9 @@ func (c memoryExecutorContext) math_Acos(arguments []interface{}, row RowType) i
|
|||||||
return math.Acos(val) * 180 / math.Pi
|
return math.Acos(val) * 180 / math.Pi
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c memoryExecutorContext) math_Asin(arguments []interface{}, row RowType) interface{} {
|
func (r rowContext) math_Asin(arguments []interface{}) interface{} {
|
||||||
exItem := arguments[0].(parsers.SelectItem)
|
exItem := arguments[0].(parsers.SelectItem)
|
||||||
ex := c.getFieldValue(exItem, row)
|
ex := r.resolveSelectItem(exItem)
|
||||||
|
|
||||||
val, valIsNumber := numToFloat64(ex)
|
val, valIsNumber := numToFloat64(ex)
|
||||||
if !valIsNumber {
|
if !valIsNumber {
|
||||||
@@ -62,9 +62,9 @@ func (c memoryExecutorContext) math_Asin(arguments []interface{}, row RowType) i
|
|||||||
return math.Asin(val) * 180 / math.Pi
|
return math.Asin(val) * 180 / math.Pi
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c memoryExecutorContext) math_Atan(arguments []interface{}, row RowType) interface{} {
|
func (r rowContext) math_Atan(arguments []interface{}) interface{} {
|
||||||
exItem := arguments[0].(parsers.SelectItem)
|
exItem := arguments[0].(parsers.SelectItem)
|
||||||
ex := c.getFieldValue(exItem, row)
|
ex := r.resolveSelectItem(exItem)
|
||||||
|
|
||||||
val, valIsNumber := numToFloat64(ex)
|
val, valIsNumber := numToFloat64(ex)
|
||||||
if !valIsNumber {
|
if !valIsNumber {
|
||||||
@@ -75,9 +75,9 @@ func (c memoryExecutorContext) math_Atan(arguments []interface{}, row RowType) i
|
|||||||
return math.Atan(val) * 180 / math.Pi
|
return math.Atan(val) * 180 / math.Pi
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c memoryExecutorContext) math_Ceiling(arguments []interface{}, row RowType) interface{} {
|
func (r rowContext) math_Ceiling(arguments []interface{}) interface{} {
|
||||||
exItem := arguments[0].(parsers.SelectItem)
|
exItem := arguments[0].(parsers.SelectItem)
|
||||||
ex := c.getFieldValue(exItem, row)
|
ex := r.resolveSelectItem(exItem)
|
||||||
|
|
||||||
switch val := ex.(type) {
|
switch val := ex.(type) {
|
||||||
case float64:
|
case float64:
|
||||||
@@ -90,9 +90,9 @@ func (c memoryExecutorContext) math_Ceiling(arguments []interface{}, row RowType
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c memoryExecutorContext) math_Cos(arguments []interface{}, row RowType) interface{} {
|
func (r rowContext) math_Cos(arguments []interface{}) interface{} {
|
||||||
exItem := arguments[0].(parsers.SelectItem)
|
exItem := arguments[0].(parsers.SelectItem)
|
||||||
ex := c.getFieldValue(exItem, row)
|
ex := r.resolveSelectItem(exItem)
|
||||||
|
|
||||||
val, valIsNumber := numToFloat64(ex)
|
val, valIsNumber := numToFloat64(ex)
|
||||||
if !valIsNumber {
|
if !valIsNumber {
|
||||||
@@ -103,9 +103,9 @@ func (c memoryExecutorContext) math_Cos(arguments []interface{}, row RowType) in
|
|||||||
return math.Cos(val)
|
return math.Cos(val)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c memoryExecutorContext) math_Cot(arguments []interface{}, row RowType) interface{} {
|
func (r rowContext) math_Cot(arguments []interface{}) interface{} {
|
||||||
exItem := arguments[0].(parsers.SelectItem)
|
exItem := arguments[0].(parsers.SelectItem)
|
||||||
ex := c.getFieldValue(exItem, row)
|
ex := r.resolveSelectItem(exItem)
|
||||||
|
|
||||||
val, valIsNumber := numToFloat64(ex)
|
val, valIsNumber := numToFloat64(ex)
|
||||||
if !valIsNumber {
|
if !valIsNumber {
|
||||||
@@ -121,9 +121,9 @@ func (c memoryExecutorContext) math_Cot(arguments []interface{}, row RowType) in
|
|||||||
return 1 / math.Tan(val)
|
return 1 / math.Tan(val)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c memoryExecutorContext) math_Degrees(arguments []interface{}, row RowType) interface{} {
|
func (r rowContext) math_Degrees(arguments []interface{}) interface{} {
|
||||||
exItem := arguments[0].(parsers.SelectItem)
|
exItem := arguments[0].(parsers.SelectItem)
|
||||||
ex := c.getFieldValue(exItem, row)
|
ex := r.resolveSelectItem(exItem)
|
||||||
|
|
||||||
val, valIsNumber := numToFloat64(ex)
|
val, valIsNumber := numToFloat64(ex)
|
||||||
if !valIsNumber {
|
if !valIsNumber {
|
||||||
@@ -134,9 +134,9 @@ func (c memoryExecutorContext) math_Degrees(arguments []interface{}, row RowType
|
|||||||
return val * (180 / math.Pi)
|
return val * (180 / math.Pi)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c memoryExecutorContext) math_Exp(arguments []interface{}, row RowType) interface{} {
|
func (r rowContext) math_Exp(arguments []interface{}) interface{} {
|
||||||
exItem := arguments[0].(parsers.SelectItem)
|
exItem := arguments[0].(parsers.SelectItem)
|
||||||
ex := c.getFieldValue(exItem, row)
|
ex := r.resolveSelectItem(exItem)
|
||||||
|
|
||||||
val, valIsNumber := numToFloat64(ex)
|
val, valIsNumber := numToFloat64(ex)
|
||||||
if !valIsNumber {
|
if !valIsNumber {
|
||||||
@@ -147,9 +147,9 @@ func (c memoryExecutorContext) math_Exp(arguments []interface{}, row RowType) in
|
|||||||
return math.Exp(val)
|
return math.Exp(val)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c memoryExecutorContext) math_Floor(arguments []interface{}, row RowType) interface{} {
|
func (r rowContext) math_Floor(arguments []interface{}) interface{} {
|
||||||
exItem := arguments[0].(parsers.SelectItem)
|
exItem := arguments[0].(parsers.SelectItem)
|
||||||
ex := c.getFieldValue(exItem, row)
|
ex := r.resolveSelectItem(exItem)
|
||||||
|
|
||||||
switch val := ex.(type) {
|
switch val := ex.(type) {
|
||||||
case float64:
|
case float64:
|
||||||
@@ -162,9 +162,9 @@ func (c memoryExecutorContext) math_Floor(arguments []interface{}, row RowType)
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c memoryExecutorContext) math_IntBitNot(arguments []interface{}, row RowType) interface{} {
|
func (r rowContext) math_IntBitNot(arguments []interface{}) interface{} {
|
||||||
exItem := arguments[0].(parsers.SelectItem)
|
exItem := arguments[0].(parsers.SelectItem)
|
||||||
ex := c.getFieldValue(exItem, row)
|
ex := r.resolveSelectItem(exItem)
|
||||||
|
|
||||||
switch val := ex.(type) {
|
switch val := ex.(type) {
|
||||||
case int:
|
case int:
|
||||||
@@ -175,9 +175,9 @@ func (c memoryExecutorContext) math_IntBitNot(arguments []interface{}, row RowTy
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c memoryExecutorContext) math_Log10(arguments []interface{}, row RowType) interface{} {
|
func (r rowContext) math_Log10(arguments []interface{}) interface{} {
|
||||||
exItem := arguments[0].(parsers.SelectItem)
|
exItem := arguments[0].(parsers.SelectItem)
|
||||||
ex := c.getFieldValue(exItem, row)
|
ex := r.resolveSelectItem(exItem)
|
||||||
|
|
||||||
val, valIsNumber := numToFloat64(ex)
|
val, valIsNumber := numToFloat64(ex)
|
||||||
if !valIsNumber {
|
if !valIsNumber {
|
||||||
@@ -193,9 +193,9 @@ func (c memoryExecutorContext) math_Log10(arguments []interface{}, row RowType)
|
|||||||
return math.Log10(val)
|
return math.Log10(val)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c memoryExecutorContext) math_Radians(arguments []interface{}, row RowType) interface{} {
|
func (r rowContext) math_Radians(arguments []interface{}) interface{} {
|
||||||
exItem := arguments[0].(parsers.SelectItem)
|
exItem := arguments[0].(parsers.SelectItem)
|
||||||
ex := c.getFieldValue(exItem, row)
|
ex := r.resolveSelectItem(exItem)
|
||||||
|
|
||||||
val, valIsNumber := numToFloat64(ex)
|
val, valIsNumber := numToFloat64(ex)
|
||||||
if !valIsNumber {
|
if !valIsNumber {
|
||||||
@@ -206,9 +206,9 @@ func (c memoryExecutorContext) math_Radians(arguments []interface{}, row RowType
|
|||||||
return val * (math.Pi / 180.0)
|
return val * (math.Pi / 180.0)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c memoryExecutorContext) math_Round(arguments []interface{}, row RowType) interface{} {
|
func (r rowContext) math_Round(arguments []interface{}) interface{} {
|
||||||
exItem := arguments[0].(parsers.SelectItem)
|
exItem := arguments[0].(parsers.SelectItem)
|
||||||
ex := c.getFieldValue(exItem, row)
|
ex := r.resolveSelectItem(exItem)
|
||||||
|
|
||||||
switch val := ex.(type) {
|
switch val := ex.(type) {
|
||||||
case float64:
|
case float64:
|
||||||
@@ -221,9 +221,9 @@ func (c memoryExecutorContext) math_Round(arguments []interface{}, row RowType)
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c memoryExecutorContext) math_Sign(arguments []interface{}, row RowType) interface{} {
|
func (r rowContext) math_Sign(arguments []interface{}) interface{} {
|
||||||
exItem := arguments[0].(parsers.SelectItem)
|
exItem := arguments[0].(parsers.SelectItem)
|
||||||
ex := c.getFieldValue(exItem, row)
|
ex := r.resolveSelectItem(exItem)
|
||||||
|
|
||||||
switch val := ex.(type) {
|
switch val := ex.(type) {
|
||||||
case float64:
|
case float64:
|
||||||
@@ -248,9 +248,9 @@ func (c memoryExecutorContext) math_Sign(arguments []interface{}, row RowType) i
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c memoryExecutorContext) math_Sin(arguments []interface{}, row RowType) interface{} {
|
func (r rowContext) math_Sin(arguments []interface{}) interface{} {
|
||||||
exItem := arguments[0].(parsers.SelectItem)
|
exItem := arguments[0].(parsers.SelectItem)
|
||||||
ex := c.getFieldValue(exItem, row)
|
ex := r.resolveSelectItem(exItem)
|
||||||
|
|
||||||
val, valIsNumber := numToFloat64(ex)
|
val, valIsNumber := numToFloat64(ex)
|
||||||
if !valIsNumber {
|
if !valIsNumber {
|
||||||
@@ -261,9 +261,9 @@ func (c memoryExecutorContext) math_Sin(arguments []interface{}, row RowType) in
|
|||||||
return math.Sin(val)
|
return math.Sin(val)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c memoryExecutorContext) math_Sqrt(arguments []interface{}, row RowType) interface{} {
|
func (r rowContext) math_Sqrt(arguments []interface{}) interface{} {
|
||||||
exItem := arguments[0].(parsers.SelectItem)
|
exItem := arguments[0].(parsers.SelectItem)
|
||||||
ex := c.getFieldValue(exItem, row)
|
ex := r.resolveSelectItem(exItem)
|
||||||
|
|
||||||
val, valIsNumber := numToFloat64(ex)
|
val, valIsNumber := numToFloat64(ex)
|
||||||
if !valIsNumber {
|
if !valIsNumber {
|
||||||
@@ -274,9 +274,9 @@ func (c memoryExecutorContext) math_Sqrt(arguments []interface{}, row RowType) i
|
|||||||
return math.Sqrt(val)
|
return math.Sqrt(val)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c memoryExecutorContext) math_Square(arguments []interface{}, row RowType) interface{} {
|
func (r rowContext) math_Square(arguments []interface{}) interface{} {
|
||||||
exItem := arguments[0].(parsers.SelectItem)
|
exItem := arguments[0].(parsers.SelectItem)
|
||||||
ex := c.getFieldValue(exItem, row)
|
ex := r.resolveSelectItem(exItem)
|
||||||
|
|
||||||
val, valIsNumber := numToFloat64(ex)
|
val, valIsNumber := numToFloat64(ex)
|
||||||
if !valIsNumber {
|
if !valIsNumber {
|
||||||
@@ -287,9 +287,9 @@ func (c memoryExecutorContext) math_Square(arguments []interface{}, row RowType)
|
|||||||
return math.Pow(val, 2)
|
return math.Pow(val, 2)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c memoryExecutorContext) math_Tan(arguments []interface{}, row RowType) interface{} {
|
func (r rowContext) math_Tan(arguments []interface{}) interface{} {
|
||||||
exItem := arguments[0].(parsers.SelectItem)
|
exItem := arguments[0].(parsers.SelectItem)
|
||||||
ex := c.getFieldValue(exItem, row)
|
ex := r.resolveSelectItem(exItem)
|
||||||
|
|
||||||
val, valIsNumber := numToFloat64(ex)
|
val, valIsNumber := numToFloat64(ex)
|
||||||
if !valIsNumber {
|
if !valIsNumber {
|
||||||
@@ -300,9 +300,9 @@ func (c memoryExecutorContext) math_Tan(arguments []interface{}, row RowType) in
|
|||||||
return math.Tan(val)
|
return math.Tan(val)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c memoryExecutorContext) math_Trunc(arguments []interface{}, row RowType) interface{} {
|
func (r rowContext) math_Trunc(arguments []interface{}) interface{} {
|
||||||
exItem := arguments[0].(parsers.SelectItem)
|
exItem := arguments[0].(parsers.SelectItem)
|
||||||
ex := c.getFieldValue(exItem, row)
|
ex := r.resolveSelectItem(exItem)
|
||||||
|
|
||||||
switch val := ex.(type) {
|
switch val := ex.(type) {
|
||||||
case float64:
|
case float64:
|
||||||
@@ -315,11 +315,11 @@ func (c memoryExecutorContext) math_Trunc(arguments []interface{}, row RowType)
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c memoryExecutorContext) math_Atn2(arguments []interface{}, row RowType) interface{} {
|
func (r rowContext) math_Atn2(arguments []interface{}) interface{} {
|
||||||
exItem1 := arguments[0].(parsers.SelectItem)
|
exItem1 := arguments[0].(parsers.SelectItem)
|
||||||
exItem2 := arguments[1].(parsers.SelectItem)
|
exItem2 := arguments[1].(parsers.SelectItem)
|
||||||
ex1 := c.getFieldValue(exItem1, row)
|
ex1 := r.resolveSelectItem(exItem1)
|
||||||
ex2 := c.getFieldValue(exItem2, row)
|
ex2 := r.resolveSelectItem(exItem2)
|
||||||
|
|
||||||
y, yIsNumber := numToFloat64(ex1)
|
y, yIsNumber := numToFloat64(ex1)
|
||||||
x, xIsNumber := numToFloat64(ex2)
|
x, xIsNumber := numToFloat64(ex2)
|
||||||
@@ -332,11 +332,11 @@ func (c memoryExecutorContext) math_Atn2(arguments []interface{}, row RowType) i
|
|||||||
return math.Atan2(y, x)
|
return math.Atan2(y, x)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c memoryExecutorContext) math_IntAdd(arguments []interface{}, row RowType) interface{} {
|
func (r rowContext) math_IntAdd(arguments []interface{}) interface{} {
|
||||||
exItem1 := arguments[0].(parsers.SelectItem)
|
exItem1 := arguments[0].(parsers.SelectItem)
|
||||||
exItem2 := arguments[1].(parsers.SelectItem)
|
exItem2 := arguments[1].(parsers.SelectItem)
|
||||||
ex1 := c.getFieldValue(exItem1, row)
|
ex1 := r.resolveSelectItem(exItem1)
|
||||||
ex2 := c.getFieldValue(exItem2, row)
|
ex2 := r.resolveSelectItem(exItem2)
|
||||||
|
|
||||||
ex1Number, ex1IsNumber := numToInt(ex1)
|
ex1Number, ex1IsNumber := numToInt(ex1)
|
||||||
ex2Number, ex2IsNumber := numToInt(ex2)
|
ex2Number, ex2IsNumber := numToInt(ex2)
|
||||||
@@ -349,11 +349,11 @@ func (c memoryExecutorContext) math_IntAdd(arguments []interface{}, row RowType)
|
|||||||
return ex1Number + ex2Number
|
return ex1Number + ex2Number
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c memoryExecutorContext) math_IntBitAnd(arguments []interface{}, row RowType) interface{} {
|
func (r rowContext) math_IntBitAnd(arguments []interface{}) interface{} {
|
||||||
exItem1 := arguments[0].(parsers.SelectItem)
|
exItem1 := arguments[0].(parsers.SelectItem)
|
||||||
exItem2 := arguments[1].(parsers.SelectItem)
|
exItem2 := arguments[1].(parsers.SelectItem)
|
||||||
ex1 := c.getFieldValue(exItem1, row)
|
ex1 := r.resolveSelectItem(exItem1)
|
||||||
ex2 := c.getFieldValue(exItem2, row)
|
ex2 := r.resolveSelectItem(exItem2)
|
||||||
|
|
||||||
ex1Int, ex1IsInt := numToInt(ex1)
|
ex1Int, ex1IsInt := numToInt(ex1)
|
||||||
ex2Int, ex2IsInt := numToInt(ex2)
|
ex2Int, ex2IsInt := numToInt(ex2)
|
||||||
@@ -366,11 +366,11 @@ func (c memoryExecutorContext) math_IntBitAnd(arguments []interface{}, row RowTy
|
|||||||
return ex1Int & ex2Int
|
return ex1Int & ex2Int
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c memoryExecutorContext) math_IntBitLeftShift(arguments []interface{}, row RowType) interface{} {
|
func (r rowContext) math_IntBitLeftShift(arguments []interface{}) interface{} {
|
||||||
exItem1 := arguments[0].(parsers.SelectItem)
|
exItem1 := arguments[0].(parsers.SelectItem)
|
||||||
exItem2 := arguments[1].(parsers.SelectItem)
|
exItem2 := arguments[1].(parsers.SelectItem)
|
||||||
ex1 := c.getFieldValue(exItem1, row)
|
ex1 := r.resolveSelectItem(exItem1)
|
||||||
ex2 := c.getFieldValue(exItem2, row)
|
ex2 := r.resolveSelectItem(exItem2)
|
||||||
|
|
||||||
num1, num1IsInt := numToInt(ex1)
|
num1, num1IsInt := numToInt(ex1)
|
||||||
num2, num2IsInt := numToInt(ex2)
|
num2, num2IsInt := numToInt(ex2)
|
||||||
@@ -383,11 +383,11 @@ func (c memoryExecutorContext) math_IntBitLeftShift(arguments []interface{}, row
|
|||||||
return num1 << uint(num2)
|
return num1 << uint(num2)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c memoryExecutorContext) math_IntBitOr(arguments []interface{}, row RowType) interface{} {
|
func (r rowContext) math_IntBitOr(arguments []interface{}) interface{} {
|
||||||
exItem1 := arguments[0].(parsers.SelectItem)
|
exItem1 := arguments[0].(parsers.SelectItem)
|
||||||
exItem2 := arguments[1].(parsers.SelectItem)
|
exItem2 := arguments[1].(parsers.SelectItem)
|
||||||
ex1 := c.getFieldValue(exItem1, row)
|
ex1 := r.resolveSelectItem(exItem1)
|
||||||
ex2 := c.getFieldValue(exItem2, row)
|
ex2 := r.resolveSelectItem(exItem2)
|
||||||
|
|
||||||
num1, num1IsInt := ex1.(int)
|
num1, num1IsInt := ex1.(int)
|
||||||
num2, num2IsInt := ex2.(int)
|
num2, num2IsInt := ex2.(int)
|
||||||
@@ -400,11 +400,11 @@ func (c memoryExecutorContext) math_IntBitOr(arguments []interface{}, row RowTyp
|
|||||||
return num1 | num2
|
return num1 | num2
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c memoryExecutorContext) math_IntBitRightShift(arguments []interface{}, row RowType) interface{} {
|
func (r rowContext) math_IntBitRightShift(arguments []interface{}) interface{} {
|
||||||
exItem1 := arguments[0].(parsers.SelectItem)
|
exItem1 := arguments[0].(parsers.SelectItem)
|
||||||
exItem2 := arguments[1].(parsers.SelectItem)
|
exItem2 := arguments[1].(parsers.SelectItem)
|
||||||
ex1 := c.getFieldValue(exItem1, row)
|
ex1 := r.resolveSelectItem(exItem1)
|
||||||
ex2 := c.getFieldValue(exItem2, row)
|
ex2 := r.resolveSelectItem(exItem2)
|
||||||
|
|
||||||
num1, num1IsInt := numToInt(ex1)
|
num1, num1IsInt := numToInt(ex1)
|
||||||
num2, num2IsInt := numToInt(ex2)
|
num2, num2IsInt := numToInt(ex2)
|
||||||
@@ -417,11 +417,11 @@ func (c memoryExecutorContext) math_IntBitRightShift(arguments []interface{}, ro
|
|||||||
return num1 >> uint(num2)
|
return num1 >> uint(num2)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c memoryExecutorContext) math_IntBitXor(arguments []interface{}, row RowType) interface{} {
|
func (r rowContext) math_IntBitXor(arguments []interface{}) interface{} {
|
||||||
exItem1 := arguments[0].(parsers.SelectItem)
|
exItem1 := arguments[0].(parsers.SelectItem)
|
||||||
exItem2 := arguments[1].(parsers.SelectItem)
|
exItem2 := arguments[1].(parsers.SelectItem)
|
||||||
ex1 := c.getFieldValue(exItem1, row)
|
ex1 := r.resolveSelectItem(exItem1)
|
||||||
ex2 := c.getFieldValue(exItem2, row)
|
ex2 := r.resolveSelectItem(exItem2)
|
||||||
|
|
||||||
num1, num1IsInt := ex1.(int)
|
num1, num1IsInt := ex1.(int)
|
||||||
num2, num2IsInt := ex2.(int)
|
num2, num2IsInt := ex2.(int)
|
||||||
@@ -434,11 +434,11 @@ func (c memoryExecutorContext) math_IntBitXor(arguments []interface{}, row RowTy
|
|||||||
return num1 ^ num2
|
return num1 ^ num2
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c memoryExecutorContext) math_IntDiv(arguments []interface{}, row RowType) interface{} {
|
func (r rowContext) math_IntDiv(arguments []interface{}) interface{} {
|
||||||
exItem1 := arguments[0].(parsers.SelectItem)
|
exItem1 := arguments[0].(parsers.SelectItem)
|
||||||
exItem2 := arguments[1].(parsers.SelectItem)
|
exItem2 := arguments[1].(parsers.SelectItem)
|
||||||
ex1 := c.getFieldValue(exItem1, row)
|
ex1 := r.resolveSelectItem(exItem1)
|
||||||
ex2 := c.getFieldValue(exItem2, row)
|
ex2 := r.resolveSelectItem(exItem2)
|
||||||
|
|
||||||
num1, num1IsInt := ex1.(int)
|
num1, num1IsInt := ex1.(int)
|
||||||
num2, num2IsInt := ex2.(int)
|
num2, num2IsInt := ex2.(int)
|
||||||
@@ -451,11 +451,11 @@ func (c memoryExecutorContext) math_IntDiv(arguments []interface{}, row RowType)
|
|||||||
return num1 / num2
|
return num1 / num2
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c memoryExecutorContext) math_IntMul(arguments []interface{}, row RowType) interface{} {
|
func (r rowContext) math_IntMul(arguments []interface{}) interface{} {
|
||||||
exItem1 := arguments[0].(parsers.SelectItem)
|
exItem1 := arguments[0].(parsers.SelectItem)
|
||||||
exItem2 := arguments[1].(parsers.SelectItem)
|
exItem2 := arguments[1].(parsers.SelectItem)
|
||||||
ex1 := c.getFieldValue(exItem1, row)
|
ex1 := r.resolveSelectItem(exItem1)
|
||||||
ex2 := c.getFieldValue(exItem2, row)
|
ex2 := r.resolveSelectItem(exItem2)
|
||||||
|
|
||||||
num1, num1IsInt := ex1.(int)
|
num1, num1IsInt := ex1.(int)
|
||||||
num2, num2IsInt := ex2.(int)
|
num2, num2IsInt := ex2.(int)
|
||||||
@@ -468,11 +468,11 @@ func (c memoryExecutorContext) math_IntMul(arguments []interface{}, row RowType)
|
|||||||
return num1 * num2
|
return num1 * num2
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c memoryExecutorContext) math_IntSub(arguments []interface{}, row RowType) interface{} {
|
func (r rowContext) math_IntSub(arguments []interface{}) interface{} {
|
||||||
exItem1 := arguments[0].(parsers.SelectItem)
|
exItem1 := arguments[0].(parsers.SelectItem)
|
||||||
exItem2 := arguments[1].(parsers.SelectItem)
|
exItem2 := arguments[1].(parsers.SelectItem)
|
||||||
ex1 := c.getFieldValue(exItem1, row)
|
ex1 := r.resolveSelectItem(exItem1)
|
||||||
ex2 := c.getFieldValue(exItem2, row)
|
ex2 := r.resolveSelectItem(exItem2)
|
||||||
|
|
||||||
num1, num1IsInt := ex1.(int)
|
num1, num1IsInt := ex1.(int)
|
||||||
num2, num2IsInt := ex2.(int)
|
num2, num2IsInt := ex2.(int)
|
||||||
@@ -485,11 +485,11 @@ func (c memoryExecutorContext) math_IntSub(arguments []interface{}, row RowType)
|
|||||||
return num1 - num2
|
return num1 - num2
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c memoryExecutorContext) math_IntMod(arguments []interface{}, row RowType) interface{} {
|
func (r rowContext) math_IntMod(arguments []interface{}) interface{} {
|
||||||
exItem1 := arguments[0].(parsers.SelectItem)
|
exItem1 := arguments[0].(parsers.SelectItem)
|
||||||
exItem2 := arguments[1].(parsers.SelectItem)
|
exItem2 := arguments[1].(parsers.SelectItem)
|
||||||
ex1 := c.getFieldValue(exItem1, row)
|
ex1 := r.resolveSelectItem(exItem1)
|
||||||
ex2 := c.getFieldValue(exItem2, row)
|
ex2 := r.resolveSelectItem(exItem2)
|
||||||
|
|
||||||
num1, num1IsInt := ex1.(int)
|
num1, num1IsInt := ex1.(int)
|
||||||
num2, num2IsInt := ex2.(int)
|
num2, num2IsInt := ex2.(int)
|
||||||
@@ -502,11 +502,11 @@ func (c memoryExecutorContext) math_IntMod(arguments []interface{}, row RowType)
|
|||||||
return num1 % num2
|
return num1 % num2
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c memoryExecutorContext) math_Power(arguments []interface{}, row RowType) interface{} {
|
func (r rowContext) math_Power(arguments []interface{}) interface{} {
|
||||||
exItem1 := arguments[0].(parsers.SelectItem)
|
exItem1 := arguments[0].(parsers.SelectItem)
|
||||||
exItem2 := arguments[1].(parsers.SelectItem)
|
exItem2 := arguments[1].(parsers.SelectItem)
|
||||||
ex1 := c.getFieldValue(exItem1, row)
|
ex1 := r.resolveSelectItem(exItem1)
|
||||||
ex2 := c.getFieldValue(exItem2, row)
|
ex2 := r.resolveSelectItem(exItem2)
|
||||||
|
|
||||||
base, baseIsNumber := numToFloat64(ex1)
|
base, baseIsNumber := numToFloat64(ex1)
|
||||||
exponent, exponentIsNumber := numToFloat64(ex2)
|
exponent, exponentIsNumber := numToFloat64(ex2)
|
||||||
@@ -519,14 +519,14 @@ func (c memoryExecutorContext) math_Power(arguments []interface{}, row RowType)
|
|||||||
return math.Pow(base, exponent)
|
return math.Pow(base, exponent)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c memoryExecutorContext) math_Log(arguments []interface{}, row RowType) interface{} {
|
func (r rowContext) math_Log(arguments []interface{}) interface{} {
|
||||||
exItem1 := arguments[0].(parsers.SelectItem)
|
exItem1 := arguments[0].(parsers.SelectItem)
|
||||||
ex := c.getFieldValue(exItem1, row)
|
ex := r.resolveSelectItem(exItem1)
|
||||||
|
|
||||||
var base float64 = math.E
|
var base float64 = math.E
|
||||||
if len(arguments) > 1 {
|
if len(arguments) > 1 {
|
||||||
exItem2 := arguments[1].(parsers.SelectItem)
|
exItem2 := arguments[1].(parsers.SelectItem)
|
||||||
baseValueObject := c.getFieldValue(exItem2, row)
|
baseValueObject := r.resolveSelectItem(exItem2)
|
||||||
baseValue, baseValueIsNumber := numToFloat64(baseValueObject)
|
baseValue, baseValueIsNumber := numToFloat64(baseValueObject)
|
||||||
|
|
||||||
if !baseValueIsNumber {
|
if !baseValueIsNumber {
|
||||||
@@ -551,15 +551,15 @@ func (c memoryExecutorContext) math_Log(arguments []interface{}, row RowType) in
|
|||||||
return math.Log(num) / math.Log(base)
|
return math.Log(num) / math.Log(base)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c memoryExecutorContext) math_NumberBin(arguments []interface{}, row RowType) interface{} {
|
func (r rowContext) math_NumberBin(arguments []interface{}) interface{} {
|
||||||
exItem1 := arguments[0].(parsers.SelectItem)
|
exItem1 := arguments[0].(parsers.SelectItem)
|
||||||
ex := c.getFieldValue(exItem1, row)
|
ex := r.resolveSelectItem(exItem1)
|
||||||
|
|
||||||
binSize := 1.0
|
binSize := 1.0
|
||||||
|
|
||||||
if len(arguments) > 1 {
|
if len(arguments) > 1 {
|
||||||
exItem2 := arguments[1].(parsers.SelectItem)
|
exItem2 := arguments[1].(parsers.SelectItem)
|
||||||
binSizeValueObject := c.getFieldValue(exItem2, row)
|
binSizeValueObject := r.resolveSelectItem(exItem2)
|
||||||
binSizeValue, binSizeValueIsNumber := numToFloat64(binSizeValueObject)
|
binSizeValue, binSizeValueIsNumber := numToFloat64(binSizeValueObject)
|
||||||
|
|
||||||
if !binSizeValueIsNumber {
|
if !binSizeValueIsNumber {
|
||||||
@@ -584,11 +584,11 @@ func (c memoryExecutorContext) math_NumberBin(arguments []interface{}, row RowTy
|
|||||||
return math.Floor(num/binSize) * binSize
|
return math.Floor(num/binSize) * binSize
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c memoryExecutorContext) math_Pi() interface{} {
|
func (r rowContext) math_Pi() interface{} {
|
||||||
return math.Pi
|
return math.Pi
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c memoryExecutorContext) math_Rand() interface{} {
|
func (r rowContext) math_Rand() interface{} {
|
||||||
return rand.Float64()
|
return rand.Float64()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -4,11 +4,11 @@ import (
|
|||||||
"github.com/pikami/cosmium/parsers"
|
"github.com/pikami/cosmium/parsers"
|
||||||
)
|
)
|
||||||
|
|
||||||
func (c memoryExecutorContext) misc_In(arguments []interface{}, row RowType) bool {
|
func (r rowContext) misc_In(arguments []interface{}) bool {
|
||||||
value := c.getFieldValue(arguments[0].(parsers.SelectItem), row)
|
value := r.resolveSelectItem(arguments[0].(parsers.SelectItem))
|
||||||
|
|
||||||
for i := 1; i < len(arguments); i++ {
|
for i := 1; i < len(arguments); i++ {
|
||||||
compareValue := c.getFieldValue(arguments[i].(parsers.SelectItem), row)
|
compareValue := r.resolveSelectItem(arguments[i].(parsers.SelectItem))
|
||||||
if compareValues(value, compareValue) == 0 {
|
if compareValues(value, compareValue) == 0 {
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ func testQueryExecute(
|
|||||||
data []memoryexecutor.RowType,
|
data []memoryexecutor.RowType,
|
||||||
expectedData []memoryexecutor.RowType,
|
expectedData []memoryexecutor.RowType,
|
||||||
) {
|
) {
|
||||||
result := memoryexecutor.Execute(query, data)
|
result := memoryexecutor.ExecuteQuery(query, data)
|
||||||
|
|
||||||
if !reflect.DeepEqual(result, expectedData) {
|
if !reflect.DeepEqual(result, expectedData) {
|
||||||
t.Errorf("execution result does not match expected data.\nExpected: %+v\nGot: %+v", expectedData, result)
|
t.Errorf("execution result does not match expected data.\nExpected: %+v\nGot: %+v", expectedData, result)
|
||||||
@@ -25,8 +25,20 @@ func Test_Execute(t *testing.T) {
|
|||||||
mockData := []memoryexecutor.RowType{
|
mockData := []memoryexecutor.RowType{
|
||||||
map[string]interface{}{"id": "12345", "pk": 123, "_self": "self1", "_rid": "rid1", "_ts": 123456, "isCool": false},
|
map[string]interface{}{"id": "12345", "pk": 123, "_self": "self1", "_rid": "rid1", "_ts": 123456, "isCool": false},
|
||||||
map[string]interface{}{"id": "67890", "pk": 456, "_self": "self2", "_rid": "rid2", "_ts": 789012, "isCool": true},
|
map[string]interface{}{"id": "67890", "pk": 456, "_self": "self2", "_rid": "rid2", "_ts": 789012, "isCool": true},
|
||||||
map[string]interface{}{"id": "456", "pk": 456, "_self": "self2", "_rid": "rid2", "_ts": 789012, "isCool": true},
|
map[string]interface{}{
|
||||||
map[string]interface{}{"id": "123", "pk": 456, "_self": "self2", "_rid": "rid2", "_ts": 789012, "isCool": true},
|
"id": "456", "pk": 456, "_self": "self2", "_rid": "rid2", "_ts": 789012, "isCool": true,
|
||||||
|
"tags": []map[string]interface{}{
|
||||||
|
{"name": "tag-a"},
|
||||||
|
{"name": "tag-b"},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
map[string]interface{}{
|
||||||
|
"id": "123", "pk": 456, "_self": "self2", "_rid": "rid2", "_ts": 789012, "isCool": true,
|
||||||
|
"tags": []map[string]interface{}{
|
||||||
|
{"name": "tag-b"},
|
||||||
|
{"name": "tag-c"},
|
||||||
|
},
|
||||||
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
t.Run("Should execute SELECT with ORDER BY", func(t *testing.T) {
|
t.Run("Should execute SELECT with ORDER BY", func(t *testing.T) {
|
||||||
@@ -124,4 +136,31 @@ func Test_Execute(t *testing.T) {
|
|||||||
},
|
},
|
||||||
)
|
)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
t.Run("Should execute IN selector", func(t *testing.T) {
|
||||||
|
testQueryExecute(
|
||||||
|
t,
|
||||||
|
parsers.SelectStmt{
|
||||||
|
SelectItems: []parsers.SelectItem{
|
||||||
|
{
|
||||||
|
Path: []string{"c", "name"},
|
||||||
|
Type: parsers.SelectItemTypeField,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
Table: parsers.Table{
|
||||||
|
Value: "c",
|
||||||
|
SelectItem: parsers.SelectItem{
|
||||||
|
Path: []string{"c", "tags"},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
mockData,
|
||||||
|
[]memoryexecutor.RowType{
|
||||||
|
map[string]interface{}{"name": "tag-a"},
|
||||||
|
map[string]interface{}{"name": "tag-b"},
|
||||||
|
map[string]interface{}{"name": "tag-b"},
|
||||||
|
map[string]interface{}{"name": "tag-c"},
|
||||||
|
},
|
||||||
|
)
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -35,6 +35,29 @@ func Test_Execute_Select(t *testing.T) {
|
|||||||
)
|
)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
t.Run("Should execute SELECT with query parameters as accessor", func(t *testing.T) {
|
||||||
|
testQueryExecute(
|
||||||
|
t,
|
||||||
|
parsers.SelectStmt{
|
||||||
|
SelectItems: []parsers.SelectItem{
|
||||||
|
{Path: []string{"c", "id"}},
|
||||||
|
{Path: []string{"c", "@param"}},
|
||||||
|
},
|
||||||
|
Table: parsers.Table{Value: "c"},
|
||||||
|
Parameters: map[string]interface{}{
|
||||||
|
"@param": "pk",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
mockData,
|
||||||
|
[]memoryexecutor.RowType{
|
||||||
|
map[string]interface{}{"id": "12345", "pk": 123},
|
||||||
|
map[string]interface{}{"id": "67890", "pk": 456},
|
||||||
|
map[string]interface{}{"id": "456", "pk": 456},
|
||||||
|
map[string]interface{}{"id": "123", "pk": 456},
|
||||||
|
},
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
t.Run("Should execute SELECT DISTINCT", func(t *testing.T) {
|
t.Run("Should execute SELECT DISTINCT", func(t *testing.T) {
|
||||||
testQueryExecute(
|
testQueryExecute(
|
||||||
t,
|
t,
|
||||||
|
|||||||
@@ -8,10 +8,10 @@ import (
|
|||||||
"github.com/pikami/cosmium/parsers"
|
"github.com/pikami/cosmium/parsers"
|
||||||
)
|
)
|
||||||
|
|
||||||
func (c memoryExecutorContext) strings_StringEquals(arguments []interface{}, row RowType) bool {
|
func (r rowContext) strings_StringEquals(arguments []interface{}) bool {
|
||||||
str1 := c.parseString(arguments[0], row)
|
str1 := r.parseString(arguments[0])
|
||||||
str2 := c.parseString(arguments[1], row)
|
str2 := r.parseString(arguments[1])
|
||||||
ignoreCase := c.getBoolFlag(arguments, row)
|
ignoreCase := r.getBoolFlag(arguments)
|
||||||
|
|
||||||
if ignoreCase {
|
if ignoreCase {
|
||||||
return strings.EqualFold(str1, str2)
|
return strings.EqualFold(str1, str2)
|
||||||
@@ -20,10 +20,10 @@ func (c memoryExecutorContext) strings_StringEquals(arguments []interface{}, row
|
|||||||
return str1 == str2
|
return str1 == str2
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c memoryExecutorContext) strings_Contains(arguments []interface{}, row RowType) bool {
|
func (r rowContext) strings_Contains(arguments []interface{}) bool {
|
||||||
str1 := c.parseString(arguments[0], row)
|
str1 := r.parseString(arguments[0])
|
||||||
str2 := c.parseString(arguments[1], row)
|
str2 := r.parseString(arguments[1])
|
||||||
ignoreCase := c.getBoolFlag(arguments, row)
|
ignoreCase := r.getBoolFlag(arguments)
|
||||||
|
|
||||||
if ignoreCase {
|
if ignoreCase {
|
||||||
str1 = strings.ToLower(str1)
|
str1 = strings.ToLower(str1)
|
||||||
@@ -33,10 +33,10 @@ func (c memoryExecutorContext) strings_Contains(arguments []interface{}, row Row
|
|||||||
return strings.Contains(str1, str2)
|
return strings.Contains(str1, str2)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c memoryExecutorContext) strings_EndsWith(arguments []interface{}, row RowType) bool {
|
func (r rowContext) strings_EndsWith(arguments []interface{}) bool {
|
||||||
str1 := c.parseString(arguments[0], row)
|
str1 := r.parseString(arguments[0])
|
||||||
str2 := c.parseString(arguments[1], row)
|
str2 := r.parseString(arguments[1])
|
||||||
ignoreCase := c.getBoolFlag(arguments, row)
|
ignoreCase := r.getBoolFlag(arguments)
|
||||||
|
|
||||||
if ignoreCase {
|
if ignoreCase {
|
||||||
str1 = strings.ToLower(str1)
|
str1 = strings.ToLower(str1)
|
||||||
@@ -46,10 +46,10 @@ func (c memoryExecutorContext) strings_EndsWith(arguments []interface{}, row Row
|
|||||||
return strings.HasSuffix(str1, str2)
|
return strings.HasSuffix(str1, str2)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c memoryExecutorContext) strings_StartsWith(arguments []interface{}, row RowType) bool {
|
func (r rowContext) strings_StartsWith(arguments []interface{}) bool {
|
||||||
str1 := c.parseString(arguments[0], row)
|
str1 := r.parseString(arguments[0])
|
||||||
str2 := c.parseString(arguments[1], row)
|
str2 := r.parseString(arguments[1])
|
||||||
ignoreCase := c.getBoolFlag(arguments, row)
|
ignoreCase := r.getBoolFlag(arguments)
|
||||||
|
|
||||||
if ignoreCase {
|
if ignoreCase {
|
||||||
str1 = strings.ToLower(str1)
|
str1 = strings.ToLower(str1)
|
||||||
@@ -59,12 +59,12 @@ func (c memoryExecutorContext) strings_StartsWith(arguments []interface{}, row R
|
|||||||
return strings.HasPrefix(str1, str2)
|
return strings.HasPrefix(str1, str2)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c memoryExecutorContext) strings_Concat(arguments []interface{}, row RowType) string {
|
func (r rowContext) strings_Concat(arguments []interface{}) string {
|
||||||
result := ""
|
result := ""
|
||||||
|
|
||||||
for _, arg := range arguments {
|
for _, arg := range arguments {
|
||||||
if selectItem, ok := arg.(parsers.SelectItem); ok {
|
if selectItem, ok := arg.(parsers.SelectItem); ok {
|
||||||
value := c.getFieldValue(selectItem, row)
|
value := r.resolveSelectItem(selectItem)
|
||||||
result += convertToString(value)
|
result += convertToString(value)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -72,13 +72,13 @@ func (c memoryExecutorContext) strings_Concat(arguments []interface{}, row RowTy
|
|||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c memoryExecutorContext) strings_IndexOf(arguments []interface{}, row RowType) int {
|
func (r rowContext) strings_IndexOf(arguments []interface{}) int {
|
||||||
str1 := c.parseString(arguments[0], row)
|
str1 := r.parseString(arguments[0])
|
||||||
str2 := c.parseString(arguments[1], row)
|
str2 := r.parseString(arguments[1])
|
||||||
|
|
||||||
start := 0
|
start := 0
|
||||||
if len(arguments) > 2 && arguments[2] != nil {
|
if len(arguments) > 2 && arguments[2] != nil {
|
||||||
if startPos, ok := c.getFieldValue(arguments[2].(parsers.SelectItem), row).(int); ok {
|
if startPos, ok := r.resolveSelectItem(arguments[2].(parsers.SelectItem)).(int); ok {
|
||||||
start = startPos
|
start = startPos
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -97,26 +97,26 @@ func (c memoryExecutorContext) strings_IndexOf(arguments []interface{}, row RowT
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c memoryExecutorContext) strings_ToString(arguments []interface{}, row RowType) string {
|
func (r rowContext) strings_ToString(arguments []interface{}) string {
|
||||||
value := c.getFieldValue(arguments[0].(parsers.SelectItem), row)
|
value := r.resolveSelectItem(arguments[0].(parsers.SelectItem))
|
||||||
return convertToString(value)
|
return convertToString(value)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c memoryExecutorContext) strings_Upper(arguments []interface{}, row RowType) string {
|
func (r rowContext) strings_Upper(arguments []interface{}) string {
|
||||||
value := c.getFieldValue(arguments[0].(parsers.SelectItem), row)
|
value := r.resolveSelectItem(arguments[0].(parsers.SelectItem))
|
||||||
return strings.ToUpper(convertToString(value))
|
return strings.ToUpper(convertToString(value))
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c memoryExecutorContext) strings_Lower(arguments []interface{}, row RowType) string {
|
func (r rowContext) strings_Lower(arguments []interface{}) string {
|
||||||
value := c.getFieldValue(arguments[0].(parsers.SelectItem), row)
|
value := r.resolveSelectItem(arguments[0].(parsers.SelectItem))
|
||||||
return strings.ToLower(convertToString(value))
|
return strings.ToLower(convertToString(value))
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c memoryExecutorContext) strings_Left(arguments []interface{}, row RowType) string {
|
func (r rowContext) strings_Left(arguments []interface{}) string {
|
||||||
var ok bool
|
var ok bool
|
||||||
var length int
|
var length int
|
||||||
str := c.parseString(arguments[0], row)
|
str := r.parseString(arguments[0])
|
||||||
lengthEx := c.getFieldValue(arguments[1].(parsers.SelectItem), row)
|
lengthEx := r.resolveSelectItem(arguments[1].(parsers.SelectItem))
|
||||||
|
|
||||||
if length, ok = lengthEx.(int); !ok {
|
if length, ok = lengthEx.(int); !ok {
|
||||||
logger.Error("strings_Left - got parameters of wrong type")
|
logger.Error("strings_Left - got parameters of wrong type")
|
||||||
@@ -134,28 +134,28 @@ func (c memoryExecutorContext) strings_Left(arguments []interface{}, row RowType
|
|||||||
return str[:length]
|
return str[:length]
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c memoryExecutorContext) strings_Length(arguments []interface{}, row RowType) int {
|
func (r rowContext) strings_Length(arguments []interface{}) int {
|
||||||
str := c.parseString(arguments[0], row)
|
str := r.parseString(arguments[0])
|
||||||
return len(str)
|
return len(str)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c memoryExecutorContext) strings_LTrim(arguments []interface{}, row RowType) string {
|
func (r rowContext) strings_LTrim(arguments []interface{}) string {
|
||||||
str := c.parseString(arguments[0], row)
|
str := r.parseString(arguments[0])
|
||||||
return strings.TrimLeft(str, " ")
|
return strings.TrimLeft(str, " ")
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c memoryExecutorContext) strings_Replace(arguments []interface{}, row RowType) string {
|
func (r rowContext) strings_Replace(arguments []interface{}) string {
|
||||||
str := c.parseString(arguments[0], row)
|
str := r.parseString(arguments[0])
|
||||||
oldStr := c.parseString(arguments[1], row)
|
oldStr := r.parseString(arguments[1])
|
||||||
newStr := c.parseString(arguments[2], row)
|
newStr := r.parseString(arguments[2])
|
||||||
return strings.Replace(str, oldStr, newStr, -1)
|
return strings.Replace(str, oldStr, newStr, -1)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c memoryExecutorContext) strings_Replicate(arguments []interface{}, row RowType) string {
|
func (r rowContext) strings_Replicate(arguments []interface{}) string {
|
||||||
var ok bool
|
var ok bool
|
||||||
var times int
|
var times int
|
||||||
str := c.parseString(arguments[0], row)
|
str := r.parseString(arguments[0])
|
||||||
timesEx := c.getFieldValue(arguments[1].(parsers.SelectItem), row)
|
timesEx := r.resolveSelectItem(arguments[1].(parsers.SelectItem))
|
||||||
|
|
||||||
if times, ok = timesEx.(int); !ok {
|
if times, ok = timesEx.(int); !ok {
|
||||||
logger.Error("strings_Replicate - got parameters of wrong type")
|
logger.Error("strings_Replicate - got parameters of wrong type")
|
||||||
@@ -173,8 +173,8 @@ func (c memoryExecutorContext) strings_Replicate(arguments []interface{}, row Ro
|
|||||||
return strings.Repeat(str, times)
|
return strings.Repeat(str, times)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c memoryExecutorContext) strings_Reverse(arguments []interface{}, row RowType) string {
|
func (r rowContext) strings_Reverse(arguments []interface{}) string {
|
||||||
str := c.parseString(arguments[0], row)
|
str := r.parseString(arguments[0])
|
||||||
runes := []rune(str)
|
runes := []rune(str)
|
||||||
|
|
||||||
for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
|
for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
|
||||||
@@ -184,11 +184,11 @@ func (c memoryExecutorContext) strings_Reverse(arguments []interface{}, row RowT
|
|||||||
return string(runes)
|
return string(runes)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c memoryExecutorContext) strings_Right(arguments []interface{}, row RowType) string {
|
func (r rowContext) strings_Right(arguments []interface{}) string {
|
||||||
var ok bool
|
var ok bool
|
||||||
var length int
|
var length int
|
||||||
str := c.parseString(arguments[0], row)
|
str := r.parseString(arguments[0])
|
||||||
lengthEx := c.getFieldValue(arguments[1].(parsers.SelectItem), row)
|
lengthEx := r.resolveSelectItem(arguments[1].(parsers.SelectItem))
|
||||||
|
|
||||||
if length, ok = lengthEx.(int); !ok {
|
if length, ok = lengthEx.(int); !ok {
|
||||||
logger.Error("strings_Right - got parameters of wrong type")
|
logger.Error("strings_Right - got parameters of wrong type")
|
||||||
@@ -206,18 +206,18 @@ func (c memoryExecutorContext) strings_Right(arguments []interface{}, row RowTyp
|
|||||||
return str[len(str)-length:]
|
return str[len(str)-length:]
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c memoryExecutorContext) strings_RTrim(arguments []interface{}, row RowType) string {
|
func (r rowContext) strings_RTrim(arguments []interface{}) string {
|
||||||
str := c.parseString(arguments[0], row)
|
str := r.parseString(arguments[0])
|
||||||
return strings.TrimRight(str, " ")
|
return strings.TrimRight(str, " ")
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c memoryExecutorContext) strings_Substring(arguments []interface{}, row RowType) string {
|
func (r rowContext) strings_Substring(arguments []interface{}) string {
|
||||||
var ok bool
|
var ok bool
|
||||||
var startPos int
|
var startPos int
|
||||||
var length int
|
var length int
|
||||||
str := c.parseString(arguments[0], row)
|
str := r.parseString(arguments[0])
|
||||||
startPosEx := c.getFieldValue(arguments[1].(parsers.SelectItem), row)
|
startPosEx := r.resolveSelectItem(arguments[1].(parsers.SelectItem))
|
||||||
lengthEx := c.getFieldValue(arguments[2].(parsers.SelectItem), row)
|
lengthEx := r.resolveSelectItem(arguments[2].(parsers.SelectItem))
|
||||||
|
|
||||||
if startPos, ok = startPosEx.(int); !ok {
|
if startPos, ok = startPosEx.(int); !ok {
|
||||||
logger.Error("strings_Substring - got start parameters of wrong type")
|
logger.Error("strings_Substring - got start parameters of wrong type")
|
||||||
@@ -240,16 +240,16 @@ func (c memoryExecutorContext) strings_Substring(arguments []interface{}, row Ro
|
|||||||
return str[startPos:endPos]
|
return str[startPos:endPos]
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c memoryExecutorContext) strings_Trim(arguments []interface{}, row RowType) string {
|
func (r rowContext) strings_Trim(arguments []interface{}) string {
|
||||||
str := c.parseString(arguments[0], row)
|
str := r.parseString(arguments[0])
|
||||||
return strings.TrimSpace(str)
|
return strings.TrimSpace(str)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c memoryExecutorContext) getBoolFlag(arguments []interface{}, row RowType) bool {
|
func (r rowContext) getBoolFlag(arguments []interface{}) bool {
|
||||||
ignoreCase := false
|
ignoreCase := false
|
||||||
if len(arguments) > 2 && arguments[2] != nil {
|
if len(arguments) > 2 && arguments[2] != nil {
|
||||||
ignoreCaseItem := arguments[2].(parsers.SelectItem)
|
ignoreCaseItem := arguments[2].(parsers.SelectItem)
|
||||||
if value, ok := c.getFieldValue(ignoreCaseItem, row).(bool); ok {
|
if value, ok := r.resolveSelectItem(ignoreCaseItem).(bool); ok {
|
||||||
ignoreCase = value
|
ignoreCase = value
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -257,9 +257,9 @@ func (c memoryExecutorContext) getBoolFlag(arguments []interface{}, row RowType)
|
|||||||
return ignoreCase
|
return ignoreCase
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c memoryExecutorContext) parseString(argument interface{}, row RowType) string {
|
func (r rowContext) parseString(argument interface{}) string {
|
||||||
exItem := argument.(parsers.SelectItem)
|
exItem := argument.(parsers.SelectItem)
|
||||||
ex := c.getFieldValue(exItem, row)
|
ex := r.resolveSelectItem(exItem)
|
||||||
if str1, ok := ex.(string); ok {
|
if str1, ok := ex.(string); ok {
|
||||||
return str1
|
return str1
|
||||||
}
|
}
|
||||||
|
|||||||
155
query_executors/memory_executor/subquery_test.go
Normal file
155
query_executors/memory_executor/subquery_test.go
Normal file
@@ -0,0 +1,155 @@
|
|||||||
|
package memoryexecutor_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/pikami/cosmium/parsers"
|
||||||
|
memoryexecutor "github.com/pikami/cosmium/query_executors/memory_executor"
|
||||||
|
)
|
||||||
|
|
||||||
|
func Test_Execute_SubQuery(t *testing.T) {
|
||||||
|
mockData := []memoryexecutor.RowType{
|
||||||
|
map[string]interface{}{"id": "123", "info": map[string]interface{}{"name": "row-1"}},
|
||||||
|
map[string]interface{}{
|
||||||
|
"id": "456",
|
||||||
|
"info": map[string]interface{}{"name": "row-2"},
|
||||||
|
"tags": []map[string]interface{}{
|
||||||
|
{"name": "tag-a"},
|
||||||
|
{"name": "tag-b"},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
map[string]interface{}{
|
||||||
|
"id": "789",
|
||||||
|
"info": map[string]interface{}{"name": "row-3"},
|
||||||
|
"tags": []map[string]interface{}{
|
||||||
|
{"name": "tag-b"},
|
||||||
|
{"name": "tag-c"},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
t.Run("Should execute FROM subquery", func(t *testing.T) {
|
||||||
|
testQueryExecute(
|
||||||
|
t,
|
||||||
|
parsers.SelectStmt{
|
||||||
|
SelectItems: []parsers.SelectItem{
|
||||||
|
{Path: []string{"c", "name"}},
|
||||||
|
},
|
||||||
|
Table: parsers.Table{
|
||||||
|
Value: "c",
|
||||||
|
SelectItem: parsers.SelectItem{
|
||||||
|
Alias: "c",
|
||||||
|
Type: parsers.SelectItemTypeSubQuery,
|
||||||
|
Value: parsers.SelectStmt{
|
||||||
|
Table: parsers.Table{Value: "cc"},
|
||||||
|
SelectItems: []parsers.SelectItem{
|
||||||
|
{Path: []string{"cc", "info"}, IsTopLevel: true},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
mockData,
|
||||||
|
[]memoryexecutor.RowType{
|
||||||
|
map[string]interface{}{"name": "row-1"},
|
||||||
|
map[string]interface{}{"name": "row-2"},
|
||||||
|
map[string]interface{}{"name": "row-3"},
|
||||||
|
},
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("Should execute JOIN subquery", func(t *testing.T) {
|
||||||
|
testQueryExecute(
|
||||||
|
t,
|
||||||
|
parsers.SelectStmt{
|
||||||
|
SelectItems: []parsers.SelectItem{
|
||||||
|
{Path: []string{"c", "id"}},
|
||||||
|
{Path: []string{"cc", "name"}},
|
||||||
|
},
|
||||||
|
Table: parsers.Table{
|
||||||
|
Value: "c",
|
||||||
|
},
|
||||||
|
JoinItems: []parsers.JoinItem{
|
||||||
|
{
|
||||||
|
Table: parsers.Table{
|
||||||
|
Value: "cc",
|
||||||
|
},
|
||||||
|
SelectItem: parsers.SelectItem{
|
||||||
|
Alias: "cc",
|
||||||
|
Type: parsers.SelectItemTypeSubQuery,
|
||||||
|
Value: parsers.SelectStmt{
|
||||||
|
SelectItems: []parsers.SelectItem{
|
||||||
|
{Path: []string{"tag", "name"}},
|
||||||
|
},
|
||||||
|
Table: parsers.Table{
|
||||||
|
Value: "tag",
|
||||||
|
SelectItem: parsers.SelectItem{
|
||||||
|
Path: []string{"c", "tags"},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
mockData,
|
||||||
|
[]memoryexecutor.RowType{
|
||||||
|
map[string]interface{}{"id": "456", "name": "tag-a"},
|
||||||
|
map[string]interface{}{"id": "456", "name": "tag-b"},
|
||||||
|
map[string]interface{}{"id": "789", "name": "tag-b"},
|
||||||
|
map[string]interface{}{"id": "789", "name": "tag-c"},
|
||||||
|
},
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("Should execute JOIN EXISTS subquery", func(t *testing.T) {
|
||||||
|
testQueryExecute(
|
||||||
|
t,
|
||||||
|
parsers.SelectStmt{
|
||||||
|
SelectItems: []parsers.SelectItem{
|
||||||
|
{Path: []string{"c", "id"}},
|
||||||
|
},
|
||||||
|
Table: parsers.Table{
|
||||||
|
Value: "c",
|
||||||
|
},
|
||||||
|
JoinItems: []parsers.JoinItem{
|
||||||
|
{
|
||||||
|
Table: parsers.Table{Value: "hasTags"},
|
||||||
|
SelectItem: parsers.SelectItem{
|
||||||
|
Alias: "hasTags",
|
||||||
|
Type: parsers.SelectItemTypeSubQuery,
|
||||||
|
Value: parsers.SelectStmt{
|
||||||
|
SelectItems: []parsers.SelectItem{
|
||||||
|
{
|
||||||
|
IsTopLevel: true,
|
||||||
|
Type: parsers.SelectItemTypeSubQuery,
|
||||||
|
Value: parsers.SelectStmt{
|
||||||
|
SelectItems: []parsers.SelectItem{
|
||||||
|
{Path: []string{"tag", "name"}},
|
||||||
|
},
|
||||||
|
Table: parsers.Table{
|
||||||
|
Value: "tag",
|
||||||
|
SelectItem: parsers.SelectItem{
|
||||||
|
Path: []string{"c", "tags"},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
Exists: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
Filters: parsers.SelectItem{
|
||||||
|
Path: []string{"hasTags"},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
mockData,
|
||||||
|
[]memoryexecutor.RowType{
|
||||||
|
map[string]interface{}{"id": "456"},
|
||||||
|
map[string]interface{}{"id": "789"},
|
||||||
|
},
|
||||||
|
)
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -6,32 +6,32 @@ import (
|
|||||||
"github.com/pikami/cosmium/parsers"
|
"github.com/pikami/cosmium/parsers"
|
||||||
)
|
)
|
||||||
|
|
||||||
func (c memoryExecutorContext) typeChecking_IsDefined(arguments []interface{}, row RowType) bool {
|
func (r rowContext) typeChecking_IsDefined(arguments []interface{}) bool {
|
||||||
exItem := arguments[0].(parsers.SelectItem)
|
exItem := arguments[0].(parsers.SelectItem)
|
||||||
ex := c.getFieldValue(exItem, row)
|
ex := r.resolveSelectItem(exItem)
|
||||||
|
|
||||||
return ex != nil
|
return ex != nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c memoryExecutorContext) typeChecking_IsArray(arguments []interface{}, row RowType) bool {
|
func (r rowContext) typeChecking_IsArray(arguments []interface{}) bool {
|
||||||
exItem := arguments[0].(parsers.SelectItem)
|
exItem := arguments[0].(parsers.SelectItem)
|
||||||
ex := c.getFieldValue(exItem, row)
|
ex := r.resolveSelectItem(exItem)
|
||||||
|
|
||||||
_, isArray := ex.([]interface{})
|
_, isArray := ex.([]interface{})
|
||||||
return isArray
|
return isArray
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c memoryExecutorContext) typeChecking_IsBool(arguments []interface{}, row RowType) bool {
|
func (r rowContext) typeChecking_IsBool(arguments []interface{}) bool {
|
||||||
exItem := arguments[0].(parsers.SelectItem)
|
exItem := arguments[0].(parsers.SelectItem)
|
||||||
ex := c.getFieldValue(exItem, row)
|
ex := r.resolveSelectItem(exItem)
|
||||||
|
|
||||||
_, isBool := ex.(bool)
|
_, isBool := ex.(bool)
|
||||||
return isBool
|
return isBool
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c memoryExecutorContext) typeChecking_IsFiniteNumber(arguments []interface{}, row RowType) bool {
|
func (r rowContext) typeChecking_IsFiniteNumber(arguments []interface{}) bool {
|
||||||
exItem := arguments[0].(parsers.SelectItem)
|
exItem := arguments[0].(parsers.SelectItem)
|
||||||
ex := c.getFieldValue(exItem, row)
|
ex := r.resolveSelectItem(exItem)
|
||||||
|
|
||||||
switch num := ex.(type) {
|
switch num := ex.(type) {
|
||||||
case int:
|
case int:
|
||||||
@@ -43,41 +43,41 @@ func (c memoryExecutorContext) typeChecking_IsFiniteNumber(arguments []interface
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c memoryExecutorContext) typeChecking_IsInteger(arguments []interface{}, row RowType) bool {
|
func (r rowContext) typeChecking_IsInteger(arguments []interface{}) bool {
|
||||||
exItem := arguments[0].(parsers.SelectItem)
|
exItem := arguments[0].(parsers.SelectItem)
|
||||||
ex := c.getFieldValue(exItem, row)
|
ex := r.resolveSelectItem(exItem)
|
||||||
|
|
||||||
_, isInt := ex.(int)
|
_, isInt := ex.(int)
|
||||||
return isInt
|
return isInt
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c memoryExecutorContext) typeChecking_IsNull(arguments []interface{}, row RowType) bool {
|
func (r rowContext) typeChecking_IsNull(arguments []interface{}) bool {
|
||||||
exItem := arguments[0].(parsers.SelectItem)
|
exItem := arguments[0].(parsers.SelectItem)
|
||||||
ex := c.getFieldValue(exItem, row)
|
ex := r.resolveSelectItem(exItem)
|
||||||
|
|
||||||
return ex == nil
|
return ex == nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c memoryExecutorContext) typeChecking_IsNumber(arguments []interface{}, row RowType) bool {
|
func (r rowContext) typeChecking_IsNumber(arguments []interface{}) bool {
|
||||||
exItem := arguments[0].(parsers.SelectItem)
|
exItem := arguments[0].(parsers.SelectItem)
|
||||||
ex := c.getFieldValue(exItem, row)
|
ex := r.resolveSelectItem(exItem)
|
||||||
|
|
||||||
_, isFloat := ex.(float64)
|
_, isFloat := ex.(float64)
|
||||||
_, isInt := ex.(int)
|
_, isInt := ex.(int)
|
||||||
return isFloat || isInt
|
return isFloat || isInt
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c memoryExecutorContext) typeChecking_IsObject(arguments []interface{}, row RowType) bool {
|
func (r rowContext) typeChecking_IsObject(arguments []interface{}) bool {
|
||||||
exItem := arguments[0].(parsers.SelectItem)
|
exItem := arguments[0].(parsers.SelectItem)
|
||||||
ex := c.getFieldValue(exItem, row)
|
ex := r.resolveSelectItem(exItem)
|
||||||
|
|
||||||
_, isObject := ex.(map[string]interface{})
|
_, isObject := ex.(map[string]interface{})
|
||||||
return isObject
|
return isObject
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c memoryExecutorContext) typeChecking_IsPrimitive(arguments []interface{}, row RowType) bool {
|
func (r rowContext) typeChecking_IsPrimitive(arguments []interface{}) bool {
|
||||||
exItem := arguments[0].(parsers.SelectItem)
|
exItem := arguments[0].(parsers.SelectItem)
|
||||||
ex := c.getFieldValue(exItem, row)
|
ex := r.resolveSelectItem(exItem)
|
||||||
|
|
||||||
switch ex.(type) {
|
switch ex.(type) {
|
||||||
case bool, string, float64, int, nil:
|
case bool, string, float64, int, nil:
|
||||||
@@ -87,9 +87,9 @@ func (c memoryExecutorContext) typeChecking_IsPrimitive(arguments []interface{},
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c memoryExecutorContext) typeChecking_IsString(arguments []interface{}, row RowType) bool {
|
func (r rowContext) typeChecking_IsString(arguments []interface{}) bool {
|
||||||
exItem := arguments[0].(parsers.SelectItem)
|
exItem := arguments[0].(parsers.SelectItem)
|
||||||
ex := c.getFieldValue(exItem, row)
|
ex := r.resolveSelectItem(exItem)
|
||||||
|
|
||||||
_, isStr := ex.(string)
|
_, isStr := ex.(string)
|
||||||
return isStr
|
return isStr
|
||||||
|
|||||||
89
sharedlibrary/collections.go
Normal file
89
sharedlibrary/collections.go
Normal file
@@ -0,0 +1,89 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import "C"
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
|
||||||
|
repositorymodels "github.com/pikami/cosmium/internal/repository_models"
|
||||||
|
)
|
||||||
|
|
||||||
|
//export CreateCollection
|
||||||
|
func CreateCollection(serverName *C.char, databaseId *C.char, collectionJson *C.char) int {
|
||||||
|
serverNameStr := C.GoString(serverName)
|
||||||
|
databaseIdStr := C.GoString(databaseId)
|
||||||
|
collectionStr := C.GoString(collectionJson)
|
||||||
|
|
||||||
|
var ok bool
|
||||||
|
var serverInstance *ServerInstance
|
||||||
|
if serverInstance, ok = getInstance(serverNameStr); !ok {
|
||||||
|
return ResponseServerInstanceNotFound
|
||||||
|
}
|
||||||
|
|
||||||
|
var collection repositorymodels.Collection
|
||||||
|
err := json.Unmarshal([]byte(collectionStr), &collection)
|
||||||
|
if err != nil {
|
||||||
|
return ResponseFailedToParseRequest
|
||||||
|
}
|
||||||
|
|
||||||
|
_, code := serverInstance.repository.CreateCollection(databaseIdStr, collection)
|
||||||
|
|
||||||
|
return repositoryStatusToResponseCode(code)
|
||||||
|
}
|
||||||
|
|
||||||
|
//export GetCollection
|
||||||
|
func GetCollection(serverName *C.char, databaseId *C.char, collectionId *C.char) *C.char {
|
||||||
|
serverNameStr := C.GoString(serverName)
|
||||||
|
databaseIdStr := C.GoString(databaseId)
|
||||||
|
collectionIdStr := C.GoString(collectionId)
|
||||||
|
|
||||||
|
var ok bool
|
||||||
|
var serverInstance *ServerInstance
|
||||||
|
if serverInstance, ok = getInstance(serverNameStr); !ok {
|
||||||
|
return C.CString("")
|
||||||
|
}
|
||||||
|
|
||||||
|
collection, code := serverInstance.repository.GetCollection(databaseIdStr, collectionIdStr)
|
||||||
|
if code != repositorymodels.StatusOk {
|
||||||
|
return C.CString("")
|
||||||
|
}
|
||||||
|
|
||||||
|
collectionJson, _ := json.Marshal(collection)
|
||||||
|
return C.CString(string(collectionJson))
|
||||||
|
}
|
||||||
|
|
||||||
|
//export GetAllCollections
|
||||||
|
func GetAllCollections(serverName *C.char, databaseId *C.char) *C.char {
|
||||||
|
serverNameStr := C.GoString(serverName)
|
||||||
|
databaseIdStr := C.GoString(databaseId)
|
||||||
|
|
||||||
|
var ok bool
|
||||||
|
var serverInstance *ServerInstance
|
||||||
|
if serverInstance, ok = getInstance(serverNameStr); !ok {
|
||||||
|
return C.CString("")
|
||||||
|
}
|
||||||
|
|
||||||
|
collections, code := serverInstance.repository.GetAllCollections(databaseIdStr)
|
||||||
|
if code != repositorymodels.StatusOk {
|
||||||
|
return C.CString("")
|
||||||
|
}
|
||||||
|
|
||||||
|
collectionsJson, _ := json.Marshal(collections)
|
||||||
|
return C.CString(string(collectionsJson))
|
||||||
|
}
|
||||||
|
|
||||||
|
//export DeleteCollection
|
||||||
|
func DeleteCollection(serverName *C.char, databaseId *C.char, collectionId *C.char) int {
|
||||||
|
serverNameStr := C.GoString(serverName)
|
||||||
|
databaseIdStr := C.GoString(databaseId)
|
||||||
|
collectionIdStr := C.GoString(collectionId)
|
||||||
|
|
||||||
|
var ok bool
|
||||||
|
var serverInstance *ServerInstance
|
||||||
|
if serverInstance, ok = getInstance(serverNameStr); !ok {
|
||||||
|
return ResponseServerInstanceNotFound
|
||||||
|
}
|
||||||
|
|
||||||
|
code := serverInstance.repository.DeleteCollection(databaseIdStr, collectionIdStr)
|
||||||
|
|
||||||
|
return repositoryStatusToResponseCode(code)
|
||||||
|
}
|
||||||
89
sharedlibrary/databases.go
Normal file
89
sharedlibrary/databases.go
Normal file
@@ -0,0 +1,89 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import "C"
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
|
||||||
|
repositorymodels "github.com/pikami/cosmium/internal/repository_models"
|
||||||
|
)
|
||||||
|
|
||||||
|
//export CreateDatabase
|
||||||
|
func CreateDatabase(serverName *C.char, databaseJson *C.char) int {
|
||||||
|
serverNameStr := C.GoString(serverName)
|
||||||
|
databaseStr := C.GoString(databaseJson)
|
||||||
|
|
||||||
|
var ok bool
|
||||||
|
var serverInstance *ServerInstance
|
||||||
|
if serverInstance, ok = getInstance(serverNameStr); !ok {
|
||||||
|
return ResponseServerInstanceNotFound
|
||||||
|
}
|
||||||
|
|
||||||
|
var database repositorymodels.Database
|
||||||
|
err := json.Unmarshal([]byte(databaseStr), &database)
|
||||||
|
if err != nil {
|
||||||
|
return ResponseFailedToParseRequest
|
||||||
|
}
|
||||||
|
|
||||||
|
_, code := serverInstance.repository.CreateDatabase(database)
|
||||||
|
|
||||||
|
return repositoryStatusToResponseCode(code)
|
||||||
|
}
|
||||||
|
|
||||||
|
//export GetDatabase
|
||||||
|
func GetDatabase(serverName *C.char, databaseId *C.char) *C.char {
|
||||||
|
serverNameStr := C.GoString(serverName)
|
||||||
|
databaseIdStr := C.GoString(databaseId)
|
||||||
|
|
||||||
|
var ok bool
|
||||||
|
var serverInstance *ServerInstance
|
||||||
|
if serverInstance, ok = getInstance(serverNameStr); !ok {
|
||||||
|
return C.CString("")
|
||||||
|
}
|
||||||
|
|
||||||
|
database, code := serverInstance.repository.GetDatabase(databaseIdStr)
|
||||||
|
if code != repositorymodels.StatusOk {
|
||||||
|
return C.CString("")
|
||||||
|
}
|
||||||
|
|
||||||
|
databaseJson, _ := json.Marshal(database)
|
||||||
|
return C.CString(string(databaseJson))
|
||||||
|
}
|
||||||
|
|
||||||
|
//export GetAllDatabases
|
||||||
|
func GetAllDatabases(serverName *C.char) *C.char {
|
||||||
|
serverNameStr := C.GoString(serverName)
|
||||||
|
|
||||||
|
var ok bool
|
||||||
|
var serverInstance *ServerInstance
|
||||||
|
if serverInstance, ok = getInstance(serverNameStr); !ok {
|
||||||
|
return C.CString("")
|
||||||
|
}
|
||||||
|
|
||||||
|
databases, code := serverInstance.repository.GetAllDatabases()
|
||||||
|
if code != repositorymodels.StatusOk {
|
||||||
|
return C.CString("")
|
||||||
|
}
|
||||||
|
|
||||||
|
databasesJson, err := json.Marshal(databases)
|
||||||
|
if err != nil {
|
||||||
|
return C.CString("")
|
||||||
|
}
|
||||||
|
|
||||||
|
return C.CString(string(databasesJson))
|
||||||
|
}
|
||||||
|
|
||||||
|
//export DeleteDatabase
|
||||||
|
func DeleteDatabase(serverName *C.char, databaseId *C.char) int {
|
||||||
|
serverNameStr := C.GoString(serverName)
|
||||||
|
databaseIdStr := C.GoString(databaseId)
|
||||||
|
|
||||||
|
var ok bool
|
||||||
|
var serverInstance *ServerInstance
|
||||||
|
if serverInstance, ok = getInstance(serverNameStr); !ok {
|
||||||
|
return ResponseServerInstanceNotFound
|
||||||
|
}
|
||||||
|
|
||||||
|
code := serverInstance.repository.DeleteDatabase(databaseIdStr)
|
||||||
|
|
||||||
|
return repositoryStatusToResponseCode(code)
|
||||||
|
}
|
||||||
122
sharedlibrary/documents.go
Normal file
122
sharedlibrary/documents.go
Normal file
@@ -0,0 +1,122 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import "C"
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
|
||||||
|
repositorymodels "github.com/pikami/cosmium/internal/repository_models"
|
||||||
|
)
|
||||||
|
|
||||||
|
//export CreateDocument
|
||||||
|
func CreateDocument(serverName *C.char, databaseId *C.char, collectionId *C.char, documentJson *C.char) int {
|
||||||
|
serverNameStr := C.GoString(serverName)
|
||||||
|
databaseIdStr := C.GoString(databaseId)
|
||||||
|
collectionIdStr := C.GoString(collectionId)
|
||||||
|
documentStr := C.GoString(documentJson)
|
||||||
|
|
||||||
|
var ok bool
|
||||||
|
var serverInstance *ServerInstance
|
||||||
|
if serverInstance, ok = getInstance(serverNameStr); !ok {
|
||||||
|
return ResponseServerInstanceNotFound
|
||||||
|
}
|
||||||
|
|
||||||
|
var document repositorymodels.Document
|
||||||
|
err := json.Unmarshal([]byte(documentStr), &document)
|
||||||
|
if err != nil {
|
||||||
|
return ResponseFailedToParseRequest
|
||||||
|
}
|
||||||
|
|
||||||
|
_, code := serverInstance.repository.CreateDocument(databaseIdStr, collectionIdStr, document)
|
||||||
|
|
||||||
|
return repositoryStatusToResponseCode(code)
|
||||||
|
}
|
||||||
|
|
||||||
|
//export GetDocument
|
||||||
|
func GetDocument(serverName *C.char, databaseId *C.char, collectionId *C.char, documentId *C.char) *C.char {
|
||||||
|
serverNameStr := C.GoString(serverName)
|
||||||
|
databaseIdStr := C.GoString(databaseId)
|
||||||
|
collectionIdStr := C.GoString(collectionId)
|
||||||
|
documentIdStr := C.GoString(documentId)
|
||||||
|
|
||||||
|
var ok bool
|
||||||
|
var serverInstance *ServerInstance
|
||||||
|
if serverInstance, ok = getInstance(serverNameStr); !ok {
|
||||||
|
return C.CString("")
|
||||||
|
}
|
||||||
|
|
||||||
|
document, code := serverInstance.repository.GetDocument(databaseIdStr, collectionIdStr, documentIdStr)
|
||||||
|
if code != repositorymodels.StatusOk {
|
||||||
|
return C.CString("")
|
||||||
|
}
|
||||||
|
|
||||||
|
documentJson, _ := json.Marshal(document)
|
||||||
|
return C.CString(string(documentJson))
|
||||||
|
}
|
||||||
|
|
||||||
|
//export GetAllDocuments
|
||||||
|
func GetAllDocuments(serverName *C.char, databaseId *C.char, collectionId *C.char) *C.char {
|
||||||
|
serverNameStr := C.GoString(serverName)
|
||||||
|
databaseIdStr := C.GoString(databaseId)
|
||||||
|
collectionIdStr := C.GoString(collectionId)
|
||||||
|
|
||||||
|
var ok bool
|
||||||
|
var serverInstance *ServerInstance
|
||||||
|
if serverInstance, ok = getInstance(serverNameStr); !ok {
|
||||||
|
return C.CString("")
|
||||||
|
}
|
||||||
|
|
||||||
|
documents, code := serverInstance.repository.GetAllDocuments(databaseIdStr, collectionIdStr)
|
||||||
|
if code != repositorymodels.StatusOk {
|
||||||
|
return C.CString("")
|
||||||
|
}
|
||||||
|
|
||||||
|
documentsJson, _ := json.Marshal(documents)
|
||||||
|
return C.CString(string(documentsJson))
|
||||||
|
}
|
||||||
|
|
||||||
|
//export UpdateDocument
|
||||||
|
func UpdateDocument(serverName *C.char, databaseId *C.char, collectionId *C.char, documentId *C.char, documentJson *C.char) int {
|
||||||
|
serverNameStr := C.GoString(serverName)
|
||||||
|
databaseIdStr := C.GoString(databaseId)
|
||||||
|
collectionIdStr := C.GoString(collectionId)
|
||||||
|
documentIdStr := C.GoString(documentId)
|
||||||
|
documentStr := C.GoString(documentJson)
|
||||||
|
|
||||||
|
var ok bool
|
||||||
|
var serverInstance *ServerInstance
|
||||||
|
if serverInstance, ok = getInstance(serverNameStr); !ok {
|
||||||
|
return ResponseServerInstanceNotFound
|
||||||
|
}
|
||||||
|
|
||||||
|
var document repositorymodels.Document
|
||||||
|
err := json.Unmarshal([]byte(documentStr), &document)
|
||||||
|
if err != nil {
|
||||||
|
return ResponseFailedToParseRequest
|
||||||
|
}
|
||||||
|
|
||||||
|
code := serverInstance.repository.DeleteDocument(databaseIdStr, collectionIdStr, documentIdStr)
|
||||||
|
if code != repositorymodels.StatusOk {
|
||||||
|
return repositoryStatusToResponseCode(code)
|
||||||
|
}
|
||||||
|
|
||||||
|
_, code = serverInstance.repository.CreateDocument(databaseIdStr, collectionIdStr, document)
|
||||||
|
return repositoryStatusToResponseCode(code)
|
||||||
|
}
|
||||||
|
|
||||||
|
//export DeleteDocument
|
||||||
|
func DeleteDocument(serverName *C.char, databaseId *C.char, collectionId *C.char, documentId *C.char) int {
|
||||||
|
serverNameStr := C.GoString(serverName)
|
||||||
|
databaseIdStr := C.GoString(databaseId)
|
||||||
|
collectionIdStr := C.GoString(collectionId)
|
||||||
|
documentIdStr := C.GoString(documentId)
|
||||||
|
|
||||||
|
var ok bool
|
||||||
|
var serverInstance *ServerInstance
|
||||||
|
if serverInstance, ok = getInstance(serverNameStr); !ok {
|
||||||
|
return ResponseServerInstanceNotFound
|
||||||
|
}
|
||||||
|
|
||||||
|
code := serverInstance.repository.DeleteDocument(databaseIdStr, collectionIdStr, documentIdStr)
|
||||||
|
|
||||||
|
return repositoryStatusToResponseCode(code)
|
||||||
|
}
|
||||||
86
sharedlibrary/shared.go
Normal file
86
sharedlibrary/shared.go
Normal file
@@ -0,0 +1,86 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"sync"
|
||||||
|
|
||||||
|
"github.com/pikami/cosmium/api"
|
||||||
|
"github.com/pikami/cosmium/internal/repositories"
|
||||||
|
repositorymodels "github.com/pikami/cosmium/internal/repository_models"
|
||||||
|
)
|
||||||
|
|
||||||
|
type ServerInstance struct {
|
||||||
|
server *api.ApiServer
|
||||||
|
repository *repositories.DataRepository
|
||||||
|
}
|
||||||
|
|
||||||
|
var serverInstances map[string]*ServerInstance
|
||||||
|
var mutex sync.RWMutex
|
||||||
|
|
||||||
|
const (
|
||||||
|
ResponseSuccess = 0
|
||||||
|
|
||||||
|
ResponseUnknown = 100
|
||||||
|
ResponseFailedToParseConfiguration = 101
|
||||||
|
ResponseFailedToLoadState = 102
|
||||||
|
ResponseFailedToParseRequest = 103
|
||||||
|
ResponseServerInstanceAlreadyExists = 104
|
||||||
|
ResponseServerInstanceNotFound = 105
|
||||||
|
|
||||||
|
ResponseRepositoryNotFound = 200
|
||||||
|
ResponseRepositoryConflict = 201
|
||||||
|
ResponseRepositoryBadRequest = 202
|
||||||
|
)
|
||||||
|
|
||||||
|
func getInstance(serverName string) (*ServerInstance, bool) {
|
||||||
|
mutex.RLock()
|
||||||
|
defer mutex.RUnlock()
|
||||||
|
|
||||||
|
if serverInstances == nil {
|
||||||
|
serverInstances = make(map[string]*ServerInstance)
|
||||||
|
}
|
||||||
|
|
||||||
|
var ok bool
|
||||||
|
var serverInstance *ServerInstance
|
||||||
|
if serverInstance, ok = serverInstances[serverName]; !ok {
|
||||||
|
return nil, false
|
||||||
|
}
|
||||||
|
|
||||||
|
return serverInstance, true
|
||||||
|
}
|
||||||
|
|
||||||
|
func addInstance(serverName string, serverInstance *ServerInstance) {
|
||||||
|
mutex.Lock()
|
||||||
|
defer mutex.Unlock()
|
||||||
|
|
||||||
|
if serverInstances == nil {
|
||||||
|
serverInstances = make(map[string]*ServerInstance)
|
||||||
|
}
|
||||||
|
|
||||||
|
serverInstances[serverName] = serverInstance
|
||||||
|
}
|
||||||
|
|
||||||
|
func removeInstance(serverName string) {
|
||||||
|
mutex.Lock()
|
||||||
|
defer mutex.Unlock()
|
||||||
|
|
||||||
|
if serverInstances == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
delete(serverInstances, serverName)
|
||||||
|
}
|
||||||
|
|
||||||
|
func repositoryStatusToResponseCode(status repositorymodels.RepositoryStatus) int {
|
||||||
|
switch status {
|
||||||
|
case repositorymodels.StatusOk:
|
||||||
|
return ResponseSuccess
|
||||||
|
case repositorymodels.StatusNotFound:
|
||||||
|
return ResponseRepositoryNotFound
|
||||||
|
case repositorymodels.Conflict:
|
||||||
|
return ResponseRepositoryConflict
|
||||||
|
case repositorymodels.BadRequest:
|
||||||
|
return ResponseRepositoryBadRequest
|
||||||
|
default:
|
||||||
|
return ResponseUnknown
|
||||||
|
}
|
||||||
|
}
|
||||||
90
sharedlibrary/sharedlibrary.go
Normal file
90
sharedlibrary/sharedlibrary.go
Normal file
@@ -0,0 +1,90 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import "C"
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
|
||||||
|
"github.com/pikami/cosmium/api"
|
||||||
|
"github.com/pikami/cosmium/api/config"
|
||||||
|
"github.com/pikami/cosmium/internal/repositories"
|
||||||
|
)
|
||||||
|
|
||||||
|
//export CreateServerInstance
|
||||||
|
func CreateServerInstance(serverName *C.char, configurationJSON *C.char) int {
|
||||||
|
configStr := C.GoString(configurationJSON)
|
||||||
|
serverNameStr := C.GoString(serverName)
|
||||||
|
|
||||||
|
if _, ok := getInstance(serverNameStr); ok {
|
||||||
|
return ResponseServerInstanceAlreadyExists
|
||||||
|
}
|
||||||
|
|
||||||
|
var configuration config.ServerConfig
|
||||||
|
err := json.Unmarshal([]byte(configStr), &configuration)
|
||||||
|
if err != nil {
|
||||||
|
return ResponseFailedToParseConfiguration
|
||||||
|
}
|
||||||
|
|
||||||
|
configuration.PopulateCalculatedFields()
|
||||||
|
configuration.ApplyDefaultsToEmptyFields()
|
||||||
|
|
||||||
|
repository := repositories.NewDataRepository(repositories.RepositoryOptions{
|
||||||
|
InitialDataFilePath: configuration.InitialDataFilePath,
|
||||||
|
PersistDataFilePath: configuration.PersistDataFilePath,
|
||||||
|
})
|
||||||
|
|
||||||
|
server := api.NewApiServer(repository, configuration)
|
||||||
|
server.Start()
|
||||||
|
|
||||||
|
addInstance(serverNameStr, &ServerInstance{
|
||||||
|
server: server,
|
||||||
|
repository: repository,
|
||||||
|
})
|
||||||
|
|
||||||
|
return ResponseSuccess
|
||||||
|
}
|
||||||
|
|
||||||
|
//export StopServerInstance
|
||||||
|
func StopServerInstance(serverName *C.char) int {
|
||||||
|
serverNameStr := C.GoString(serverName)
|
||||||
|
|
||||||
|
if serverInstance, ok := getInstance(serverNameStr); ok {
|
||||||
|
serverInstance.server.Stop()
|
||||||
|
removeInstance(serverNameStr)
|
||||||
|
return ResponseSuccess
|
||||||
|
}
|
||||||
|
|
||||||
|
return ResponseServerInstanceNotFound
|
||||||
|
}
|
||||||
|
|
||||||
|
//export GetServerInstanceState
|
||||||
|
func GetServerInstanceState(serverName *C.char) *C.char {
|
||||||
|
serverNameStr := C.GoString(serverName)
|
||||||
|
|
||||||
|
if serverInstance, ok := getInstance(serverNameStr); ok {
|
||||||
|
stateJSON, err := serverInstance.repository.GetState()
|
||||||
|
if err != nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return C.CString(stateJSON)
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
//export LoadServerInstanceState
|
||||||
|
func LoadServerInstanceState(serverName *C.char, stateJSON *C.char) int {
|
||||||
|
serverNameStr := C.GoString(serverName)
|
||||||
|
stateJSONStr := C.GoString(stateJSON)
|
||||||
|
|
||||||
|
if serverInstance, ok := getInstance(serverNameStr); ok {
|
||||||
|
err := serverInstance.repository.LoadStateJSON(stateJSONStr)
|
||||||
|
if err != nil {
|
||||||
|
return ResponseFailedToLoadState
|
||||||
|
}
|
||||||
|
return ResponseSuccess
|
||||||
|
}
|
||||||
|
|
||||||
|
return ResponseServerInstanceNotFound
|
||||||
|
}
|
||||||
|
|
||||||
|
func main() {}
|
||||||
46
sharedlibrary/tests/main.c
Normal file
46
sharedlibrary/tests/main.c
Normal file
@@ -0,0 +1,46 @@
|
|||||||
|
#include "shared.h"
|
||||||
|
|
||||||
|
int test_CreateServerInstance();
|
||||||
|
int test_StopServerInstance();
|
||||||
|
int test_ServerInstanceStateMethods();
|
||||||
|
int test_Databases();
|
||||||
|
|
||||||
|
int main(int argc, char *argv[])
|
||||||
|
{
|
||||||
|
if (argc < 2)
|
||||||
|
{
|
||||||
|
fprintf(stderr, "Usage: %s <path_to_shared_library>\n", argv[0]);
|
||||||
|
return EXIT_FAILURE;
|
||||||
|
}
|
||||||
|
|
||||||
|
const char *libPath = argv[1];
|
||||||
|
handle = dlopen(libPath, RTLD_LAZY);
|
||||||
|
if (!handle)
|
||||||
|
{
|
||||||
|
fprintf(stderr, "Failed to load shared library: %s\n", dlerror());
|
||||||
|
return EXIT_FAILURE;
|
||||||
|
}
|
||||||
|
|
||||||
|
printf("Running tests for library: %s\n", libPath);
|
||||||
|
int results[] = {
|
||||||
|
test_CreateServerInstance(),
|
||||||
|
test_Databases(),
|
||||||
|
test_ServerInstanceStateMethods(),
|
||||||
|
test_StopServerInstance(),
|
||||||
|
};
|
||||||
|
|
||||||
|
int numTests = sizeof(results) / sizeof(results[0]);
|
||||||
|
int numPassed = 0;
|
||||||
|
for (int i = 0; i < numTests; i++)
|
||||||
|
{
|
||||||
|
if (results[i])
|
||||||
|
{
|
||||||
|
numPassed++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
printf("Tests passed: %d/%d\n", numPassed, numTests);
|
||||||
|
|
||||||
|
dlclose(handle);
|
||||||
|
return EXIT_SUCCESS;
|
||||||
|
}
|
||||||
36
sharedlibrary/tests/shared.c
Normal file
36
sharedlibrary/tests/shared.c
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
#include "shared.h"
|
||||||
|
|
||||||
|
void *handle = NULL;
|
||||||
|
|
||||||
|
void *load_function(const char *func_name)
|
||||||
|
{
|
||||||
|
void *func = dlsym(handle, func_name);
|
||||||
|
if (!func)
|
||||||
|
{
|
||||||
|
fprintf(stderr, "Failed to load function %s: %s\n", func_name, dlerror());
|
||||||
|
}
|
||||||
|
return func;
|
||||||
|
}
|
||||||
|
|
||||||
|
char *compact_json(const char *json)
|
||||||
|
{
|
||||||
|
size_t len = strlen(json);
|
||||||
|
char *compact = (char *)malloc(len + 1);
|
||||||
|
if (!compact)
|
||||||
|
{
|
||||||
|
fprintf(stderr, "Failed to allocate memory for compacted JSON\n");
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
|
||||||
|
char *dest = compact;
|
||||||
|
for (const char *src = json; *src != '\0'; ++src)
|
||||||
|
{
|
||||||
|
if (!isspace((unsigned char)*src)) // Skip spaces, newlines, tabs, etc.
|
||||||
|
{
|
||||||
|
*dest++ = *src;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
*dest = '\0'; // Null-terminate the string
|
||||||
|
|
||||||
|
return compact;
|
||||||
|
}
|
||||||
15
sharedlibrary/tests/shared.h
Normal file
15
sharedlibrary/tests/shared.h
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
#ifndef SHARED_H
|
||||||
|
#define SHARED_H
|
||||||
|
|
||||||
|
#include <stdio.h>
|
||||||
|
#include <stdlib.h>
|
||||||
|
#include <dlfcn.h>
|
||||||
|
#include <string.h>
|
||||||
|
#include <ctype.h>
|
||||||
|
|
||||||
|
extern void *handle;
|
||||||
|
|
||||||
|
void *load_function(const char *func_name);
|
||||||
|
char *compact_json(const char *json);
|
||||||
|
|
||||||
|
#endif
|
||||||
29
sharedlibrary/tests/test_create.c
Normal file
29
sharedlibrary/tests/test_create.c
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
#include "shared.h"
|
||||||
|
|
||||||
|
int test_CreateServerInstance()
|
||||||
|
{
|
||||||
|
typedef int (*CreateServerInstanceFn)(char *, char *);
|
||||||
|
CreateServerInstanceFn CreateServerInstance = (CreateServerInstanceFn)load_function("CreateServerInstance");
|
||||||
|
|
||||||
|
if (!CreateServerInstance)
|
||||||
|
{
|
||||||
|
fprintf(stderr, "Failed to find CreateServerInstance function\n");
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
char *serverName = "TestServer";
|
||||||
|
char *configJSON = "{\"host\":\"localhost\",\"port\":8080}";
|
||||||
|
|
||||||
|
int result = CreateServerInstance(serverName, configJSON);
|
||||||
|
if (result == 0)
|
||||||
|
{
|
||||||
|
printf("CreateServerInstance: SUCCESS\n");
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
printf("CreateServerInstance: FAILED (result = %d)\n", result);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
47
sharedlibrary/tests/test_databases.c
Normal file
47
sharedlibrary/tests/test_databases.c
Normal file
@@ -0,0 +1,47 @@
|
|||||||
|
#include "shared.h"
|
||||||
|
|
||||||
|
int test_Databases()
|
||||||
|
{
|
||||||
|
typedef int (*CreateDatabaseFn)(char *, char *);
|
||||||
|
CreateDatabaseFn CreateDatabase = (CreateDatabaseFn)load_function("CreateDatabase");
|
||||||
|
if (!CreateDatabase)
|
||||||
|
{
|
||||||
|
fprintf(stderr, "Failed to find CreateDatabase function\n");
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
char *serverName = "TestServer";
|
||||||
|
char *configJSON = "{\"id\":\"test-db\"}";
|
||||||
|
|
||||||
|
int result = CreateDatabase(serverName, configJSON);
|
||||||
|
if (result == 0)
|
||||||
|
{
|
||||||
|
printf("CreateDatabase: SUCCESS\n");
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
printf("CreateDatabase: FAILED (result = %d)\n", result);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
typedef char *(*GetDatabaseFn)(char *, char *);
|
||||||
|
GetDatabaseFn GetDatabase = (GetDatabaseFn)load_function("GetDatabase");
|
||||||
|
if (!GetDatabase)
|
||||||
|
{
|
||||||
|
fprintf(stderr, "Failed to find GetDatabase function\n");
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
char *database = GetDatabase(serverName, "test-db");
|
||||||
|
if (database)
|
||||||
|
{
|
||||||
|
printf("GetDatabase: SUCCESS (database = %s)\n", database);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
printf("GetDatabase: FAILED\n");
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
68
sharedlibrary/tests/test_instance_state.c
Normal file
68
sharedlibrary/tests/test_instance_state.c
Normal file
@@ -0,0 +1,68 @@
|
|||||||
|
#include "shared.h"
|
||||||
|
|
||||||
|
int test_ServerInstanceStateMethods()
|
||||||
|
{
|
||||||
|
typedef int (*LoadServerInstanceStateFn)(char *, char *);
|
||||||
|
LoadServerInstanceStateFn LoadServerInstanceState = (LoadServerInstanceStateFn)load_function("LoadServerInstanceState");
|
||||||
|
if (!LoadServerInstanceState)
|
||||||
|
{
|
||||||
|
fprintf(stderr, "Failed to find LoadServerInstanceState function\n");
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
char *serverName = "TestServer";
|
||||||
|
char *stateJSON = "{\"databases\":{\"test-db\":{\"id\":\"test-db\"}}}";
|
||||||
|
int result = LoadServerInstanceState(serverName, stateJSON);
|
||||||
|
if (result == 0)
|
||||||
|
{
|
||||||
|
printf("LoadServerInstanceState: SUCCESS\n");
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
printf("LoadServerInstanceState: FAILED (result = %d)\n", result);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
typedef char *(*GetServerInstanceStateFn)(char *);
|
||||||
|
GetServerInstanceStateFn GetServerInstanceState = (GetServerInstanceStateFn)load_function("GetServerInstanceState");
|
||||||
|
if (!GetServerInstanceState)
|
||||||
|
{
|
||||||
|
fprintf(stderr, "Failed to find GetServerInstanceState function\n");
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
char *state = GetServerInstanceState(serverName);
|
||||||
|
if (state)
|
||||||
|
{
|
||||||
|
printf("GetServerInstanceState: SUCCESS (state = %s)\n", state);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
printf("GetServerInstanceState: FAILED\n");
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
const char *expected_state = "{\"databases\":{\"test-db\":{\"id\":\"test-db\",\"_ts\":0,\"_rid\":\"\",\"_etag\":\"\",\"_self\":\"\"}},\"collections\":{\"test-db\":{}},\"documents\":{\"test-db\":{}}}";
|
||||||
|
char *compact_state = compact_json(state);
|
||||||
|
if (!compact_state)
|
||||||
|
{
|
||||||
|
free(state);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (strcmp(compact_state, expected_state) == 0)
|
||||||
|
{
|
||||||
|
printf("GetServerInstanceState: State matches expected value.\n");
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
printf("GetServerInstanceState: State does not match expected value.\n");
|
||||||
|
printf("Expected: %s\n", expected_state);
|
||||||
|
printf("Actual: %s\n", compact_state);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
free(state);
|
||||||
|
free(compact_state);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
27
sharedlibrary/tests/test_stop.c
Normal file
27
sharedlibrary/tests/test_stop.c
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
#include "shared.h"
|
||||||
|
|
||||||
|
int test_StopServerInstance()
|
||||||
|
{
|
||||||
|
typedef int (*StopServerInstanceFn)(char *);
|
||||||
|
StopServerInstanceFn StopServerInstance = (StopServerInstanceFn)load_function("StopServerInstance");
|
||||||
|
|
||||||
|
if (!StopServerInstance)
|
||||||
|
{
|
||||||
|
fprintf(stderr, "Failed to find StopServerInstance function\n");
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
char *serverName = "TestServer";
|
||||||
|
int result = StopServerInstance(serverName);
|
||||||
|
if (result == 0)
|
||||||
|
{
|
||||||
|
printf("StopServerInstance: SUCCESS\n");
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
printf("StopServerInstance: FAILED (result = %d)\n", result);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user