# SyntricDB — Multi-Language Developer Integration Guide 🚀

This comprehensive guide demonstrates how to integrate **SyntricDB**—the next-generation AI-native unified database engine—into your backend applications across major programming languages using the native **SyntricDB Connection String** (`syntricdb://`) and native language SDKs.

Official Examples Repository: [github.com/upendra-manike/SyntricDb_Examples](https://github.com/upendra-manike/SyntricDb_Examples)

---

## 📋 Table of Contents
1. [Native Connection URL & Authentication](#1-native-connection-url--authentication)
2. [ERM Enterprise Schema Reference](#2-erm-enterprise-schema-reference)
3. [Java & Spring Boot 3 JPA Integration](#3-java--spring-boot-3-jpa-integration)
4. [Python SDK & FastAPI Integration](#4-python-sdk--fastapi-integration)
5. [Node.js & TypeScript Integration](#5-nodejs--typescript-integration)
6. [C# & .NET 8 Integration](#6-c--net-8-integration)
7. [Go (Golang) Integration](#7-go-golang-integration)
8. [Rust Integration](#8-rust-integration)
9. [cURL & Automated Shell Scripts](#9-curl--automated-shell-scripts)

---

## 1. Native Connection URL & Authentication

SyntricDB uses a unified connection URL format across all native language drivers and SDKs:

### Connection String Format
```text
syntricdb://username:password@host:port/database
```

### JDBC Format (Java / Spring Boot)
```text
jdbc:syntricdb://username:password@host:port/database
```

| Connection Component | Description | Default Value |
| :--- | :--- | :--- |
| **Scheme** | `syntricdb://` (or `jdbc:syntricdb://` for JDBC) | `syntricdb://` |
| **Username** | Database Admin/User name | Configured during `syntricdb` installation (default: `admin`) |
| **Password** | Database Admin/User password | Configured during `syntricdb` installation (default: `syntricdb_secret_pass`) |
| **Host** | Server Hostname or IP | `localhost` |
| **Port** | SyntricDB Engine Port | `8080` |
| **Database** | Target Database Name | `default` |

---

## 2. ERM Enterprise Schema Reference

SyntricDB supports standard ANSI SQL DDL alongside native `VECTOR(dim)` types:

```sql
-- 1. Employees Table with Vector Embedding for Skills Match
CREATE TABLE IF NOT EXISTS employees (
    id VARCHAR(50) PRIMARY KEY,
    name VARCHAR(100),
    department VARCHAR(50),
    role VARCHAR(50),
    salary DECIMAL(10,2),
    skills_embedding FLOAT_VECTOR(128)
);

-- 2. Enterprise Resources Table
CREATE TABLE IF NOT EXISTS enterprise_resources (
    id VARCHAR(50) PRIMARY KEY,
    name VARCHAR(100),
    category VARCHAR(50),
    status VARCHAR(30),
    assigned_emp_id VARCHAR(50),
    cost DECIMAL(10,2)
);

-- 3. Risk Assessments Table with Vector Embedding for Semantic Search
CREATE TABLE IF NOT EXISTS risk_assessments (
    id VARCHAR(50) PRIMARY KEY,
    category VARCHAR(50),
    severity VARCHAR(20),
    description TEXT,
    vector_embedding FLOAT_VECTOR(128)
);
```

---

## 3. Java & Spring Boot 3 JPA Integration

Connect Spring Boot applications directly to SyntricDB using the official **SyntricDB Native JDBC Driver** (`com.syntricdb.jdbc.SyntricDBDriver`).

### Maven Dependency (`pom.xml`)
```xml
<dependencies>
    <!-- Spring Data JPA Starter -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>

    <!-- Spring Web MVC Starter -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <!-- SyntricDB Native JDBC Driver -->
    <dependency>
        <groupId>io.github.upendra-manike</groupId>
        <artifactId>syntricdb-java-client</artifactId>
        <version>1.0.0</version>
    </dependency>
</dependencies>
```

### Application Settings (`application.properties`)
```properties
# Dedicated SyntricDB Connection Settings
spring.datasource.url=jdbc:syntricdb://localhost:8080/default
spring.datasource.username=admin
spring.datasource.password=syntricdb_secret_pass
spring.datasource.driver-class-name=com.syntricdb.jdbc.SyntricDBDriver

# JPA & Hibernate Settings
spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect
spring.jpa.hibernate.ddl-auto=none
spring.jpa.show-sql=true
```

### Spring Data JPA Repository (`ProductRepository.java`)
```java
package com.syntricdb.repository;

import com.syntricdb.entity.Product;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface ProductRepository extends JpaRepository<Product, String> {

    // 1. Native SyntricDB SIMD HNSW Vector Search Query
    @Query(value = "SELECT * FROM products WHERE category = :cat AND embedding SIMILAR TO :term TOP :limit", nativeQuery = true)
    List<Product> searchByVectorSimilarity(@Param("cat") String category, 
                                           @Param("term") String searchTerm, 
                                           @Param("limit") int limit);

    // 2. Native In-Engine AI RAG Query
    @Query(value = "SELECT AI_RAG(:prompt)", nativeQuery = true)
    String generateAIRagResponse(@Param("prompt") String prompt);
}
```

### Spring Boot REST MVC Controller (`ProductController.java`)
```java
package com.syntricdb.controller;

import com.syntricdb.entity.Product;
import com.syntricdb.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/products")
public class ProductController {

    @Autowired
    private ProductService productService;

    @PostMapping
    public ResponseEntity<Product> createProduct(@RequestBody Product product) {
        return ResponseEntity.ok(productService.createProduct(product));
    }

    @GetMapping("/search")
    public ResponseEntity<List<Product>> searchProducts(
            @RequestParam String category,
            @RequestParam String query,
            @RequestParam(defaultValue = "5") int limit) {
        return ResponseEntity.ok(productService.searchSimilarProducts(category, query, limit));
    }

    @GetMapping("/rag")
    public ResponseEntity<Map<String, String>> askRag(@RequestParam String prompt) {
        return ResponseEntity.ok(Map.of("prompt", prompt, "answer", productService.askDatabaseRag(prompt)));
    }
}
```

---

## 4. Python SDK & FastAPI Integration

### Package Installation
```bash
pip install syntricdb-client
```

### Python ERM Script (`erm_portal.py`)
```python
from syntricdb.client import SyntricDBClient
import json

# Connect using native SyntricDB connection URL
SYNTRICDB_URL = "syntricdb://admin:syntricdb_secret_pass@localhost:8080/default"
client = SyntricDBClient(SYNTRICDB_URL)

# 1. Initialize Tables
client.query("""
CREATE TABLE IF NOT EXISTS employees (
    id VARCHAR PRIMARY KEY, 
    name VARCHAR, 
    department VARCHAR, 
    role VARCHAR, 
    salary DOUBLE, 
    skills_embedding FLOAT_VECTOR(128)
);
""")

# 2. Seed Data with Auto AI Embedding
client.query("""
INSERT INTO employees VALUES (
    'EMP-101', 
    'Alice Vance', 
    'Engineering', 
    'Lead Architect', 
    155000.00, 
    AI_EMBED('Lead Architect Engineering Distributed Systems')
);
""")

# 3. Vector Similarity Search Query
res = client.query("""
SELECT id, name, department 
FROM employees 
WHERE skills_embedding SIMILAR TO 'Distributed Systems Architect' 
TOP 1;
""")
print("Vector Match Result:", json.dumps(res, indent=2))
```

---

## 5. Node.js & TypeScript Integration

### Installation
```bash
npm install syntricdb-client
```

### Node.js Script (`erm_portal.js`)
```javascript
const { SyntricDBClient } = require('syntricdb-client');

const SYNTRICDB_URL = 'syntricdb://admin:syntricdb_secret_pass@localhost:8080/default';
const client = new SyntricDBClient(SYNTRICDB_URL);

async function run() {
  console.log('🚀 Initializing Node.js ERM Portal...');
  
  // 1. Create Table
  await client.query(`
    CREATE TABLE IF NOT EXISTS risk_assessments (
      id VARCHAR PRIMARY KEY,
      category VARCHAR,
      severity VARCHAR,
      description VARCHAR,
      vector_embedding FLOAT_VECTOR(128)
    );
  `);

  // 2. Vector Similarity Query
  const vectorRes = await client.query(`
    SELECT id, category, severity, description 
    FROM risk_assessments 
    WHERE vector_embedding SIMILAR TO 'critical security vulnerability' 
    TOP 1;
  `);
  
  console.log('Risk Vector Match:', vectorRes);
}

run().catch(console.error);
```

---

## 6. C# & .NET 8 Integration

### C# Program (`Program.cs`)
```csharp
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace SyntricDBDemo
{
    class Program
    {
        private static readonly HttpClient client = new HttpClient();
        private const string SyntricDBUrl = "syntricdb://admin:syntricdb_secret_pass@localhost:8080/default";

        static async Task Main(string[] args)
        {
            Console.WriteLine("=================================================");
            Console.WriteLine("💜 SyntricDB C# / .NET 8 Integration");
            Console.WriteLine("=================================================");

            string query = @"
                SELECT id, name, salary 
                FROM employees 
                WHERE skills_embedding SIMILAR TO 'AI Systems Architect' 
                TOP 1;";

            string jsonResult = await ExecuteQueryAsync(query);
            Console.WriteLine($"SyntricDB Results:\n{jsonResult}");
        }

        private static async Task<string> ExecuteQueryAsync(string sql)
        {
            var (apiUrl, user, pass, database) = ParseConnectionUrl(SyntricDBUrl);
            var json = JsonSerializer.Serialize(new { sql = sql, database = database });
            var content = new StringContent(json, Encoding.UTF8, "application/json");

            var request = new HttpRequestMessage(HttpMethod.Post, apiUrl) { Content = content };

            if (!string.IsNullOrEmpty(user) && !string.IsNullOrEmpty(pass))
            {
                var authBytes = Encoding.UTF8.GetBytes($"{user}:{pass}");
                request.Headers.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(authBytes));
            }

            var response = await client.SendAsync(request);
            return await response.Content.ReadAsStringAsync();
        }

        private static (string apiUrl, string user, string pass, string database) ParseConnectionUrl(string urlStr)
        {
            var cleanUrl = urlStr.Replace("jdbc:syntricdb://", "http://").Replace("syntricdb://", "http://");
            var uri = new Uri(cleanUrl);
            var host = uri.Host;
            var port = uri.Port > 0 ? uri.Port : 8080;
            var apiUrl = $"http://{host}:{port}/api/sql";

            string user = "", pass = "";
            if (!string.IsNullOrEmpty(uri.UserInfo))
            {
                var parts = uri.UserInfo.Split(':');
                if (parts.Length > 0) user = Uri.UnescapeDataString(parts[0]);
                if (parts.Length > 1) pass = Uri.UnescapeDataString(parts[1]);
            }

            var db = uri.AbsolutePath.Trim('/');
            if (string.IsNullOrEmpty(db)) db = "default";

            return (apiUrl, user, pass, db);
        }
    }
}
```

---

## 7. Go (Golang) Integration

### Go Code (`main.go`)
```go
package main

import (
	"bytes"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"net/url"
	"strings"
)

const SyntricDBURL = "syntricdb://admin:syntricdb_secret_pass@localhost:8080/default"

type QueryPayload struct {
	SQL      string `json:"sql"`
	Database string `json:"database"`
}

func parseConnectionURL(rawURL string) (string, string, string, string) {
	cleanURL := strings.Replace(rawURL, "jdbc:syntricdb://", "http://", 1)
	cleanURL = strings.Replace(cleanURL, "syntricdb://", "http://", 1)

	u, err := url.Parse(cleanURL)
	if err != nil {
		return "http://localhost:8080/api/sql", "admin", "syntricdb_secret_pass", "default"
	}

	host := u.Hostname()
	port := u.Port()
	if port == "" {
		port = "8080"
	}
	apiURL := fmt.Sprintf("http://%s:%s/api/sql", host, port)

	user := ""
	pass := ""
	if u.User != nil {
		user = u.User.Username()
		pass, _ = u.User.Password()
	}

	db := strings.Trim(u.Path, "/")
	if db == "" {
		db = "default"
	}

	return apiURL, user, pass, db
}

func executeQuery(sql string) (string, error) {
	apiURL, user, pass, database := parseConnectionURL(SyntricDBURL)
	payload := QueryPayload{SQL: sql, Database: database}
	body, _ := json.Marshal(payload)

	req, _ := http.NewRequest("POST", apiURL, bytes.NewBuffer(body))
	req.Header.Set("Content-Type", "application/json")

	if user != "" && pass != "" {
		auth := base64.StdEncoding.EncodeToString([]byte(user + ":" + pass))
		req.Header.Set("Authorization", "Basic "+auth)
	}

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()

	respBody, _ := io.ReadAll(resp.Body)
	return string(respBody), nil
}

func main() {
	res, err := executeQuery("SELECT id, name FROM employees WHERE skills_embedding SIMILAR TO 'Distributed Systems' TOP 2;")
	if err == nil {
		fmt.Println("SyntricDB Vector Matches:\n", res)
	}
}
```

---

## 8. Rust Integration

### Rust Code (`src/main.rs`)
```rust
use serde::Serialize;
use std::error::Error;

const SYNTRICDB_URL: &str = "syntricdb://admin:syntricdb_secret_pass@localhost:8080/default";

#[derive(Serialize)]
struct QueryRequest<'a> {
    sql: &'a str,
    database: &'a str,
}

fn parse_connection_url(url_str: &str) -> (String, Option<(String, String)>, String) {
    let clean = url_str
        .replace("jdbc:syntricdb://", "http://")
        .replace("syntricdb://", "http://");
    if let Ok(u) = reqwest::Url::parse(&clean) {
        let host = u.host_str().unwrap_or("localhost");
        let port = u.port().unwrap_or(8080);
        let api_url = format!("http://{}:{}/api/sql", host, port);
        
        let auth = if !u.username().is_empty() {
            Some((u.username().to_string(), u.password().unwrap_or("").to_string()))
        } else {
            None
        };

        let db = u.path().trim_start_matches('/');
        let database = if db.is_empty() { "default" } else { db };

        (api_url, auth, database.to_string())
    } else {
        ("http://localhost:8080/api/sql".to_string(), None, "default".to_string())
    }
}

async fn execute_query(sql: &str) -> Result<String, Box<dyn Error>> {
    let (api_url, auth, database) = parse_connection_url(SYNTRICDB_URL);
    let client = reqwest::Client::new();
    let body = QueryRequest { sql, database: &database };
    
    let mut req = client.post(&api_url).json(&body);
    if let Some((user, pass)) = auth {
        req = req.basic_auth(user, Some(pass));
    }

    let resp = req.send().await?.text().await?;
    Ok(resp)
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    let res = execute_query("SELECT id, name FROM employees WHERE skills_embedding SIMILAR TO 'AI Architect' TOP 1;").await?;
    println!("SyntricDB Result:\n{}", res);
    Ok(())
}
```

---

## 9. cURL & Automated Shell Scripts

```bash
# Execute SQL Query via cURL using Connection Credentials
curl -s -u admin:syntricdb_secret_pass -X POST http://localhost:8080/api/sql \
  -H "Content-Type: application/json" \
  -d '{"database": "default", "sql": "SELECT id, name, salary FROM employees WHERE salary > 100000;"}'
```

---

## 🔗 Official Open Source Links
- **SyntricDB Website**: [https://syntricdb.com](https://syntricdb.com)
- **Multi-Language Examples Repo**: [https://github.com/upendra-manike/SyntricDb_Examples](https://github.com/upendra-manike/SyntricDb_Examples)
- **Main Core Engine Repo**: [https://github.com/upendra-manike/SyntricDB](https://github.com/upendra-manike/SyntricDB)
