본문 바로가기
WIKI 기술 지식 베이스

Turso 예제

원문 보기 위키 갱신

Turso 예제 (Go)

Go용 Turso(go-libsql) 예제 모음이에요. 공식 문서의 이 페이지는 go-libsql 저장소의 example 디렉터리로 안내해요.

출처: 문서

본문

공식 문서의 이 페이지는 실제 예제 코드가 있는 go-libsql 저장소로 리다이렉트돼요. example 디렉터리에는 다음이 있어요:

  • local/ — 로컬 데이터베이스 연결 예제
  • remote/ — 원격(Turso Cloud) 데이터베이스 연결 예제
  • sync/ — 동기화 예제
  • go.mod, go.sum — 모듈 구성

예를 들어 remote/main.go는 원격 암호화 Turso Cloud 데이터베이스에 연결하는 예제예요. TURSO_URL, TURSO_AUTH_TOKEN, TURSO_REMOTE_ENCRYPTION_KEY 환경 변수를 사용해서 DSN을 만들고 sql.Open("libsql", dbUrl)로 연결한 뒤, 테이블 생성·조건부 삽입·조회를 수행해요:

// Example: Connecting to an encrypted Turso Cloud database
//
// This example shows how to connect to a Turso Cloud database with
// remote encryption using the go-libsql driver.
//
// Documentation of encrypted databases - https://docs.turso.tech/cloud/encryption
//
// Usage:
//
//	export TURSO_URL="libsql://your-db.aws-us-east-2.turso.io"
//	export TURSO_AUTH_TOKEN="your-token"
//	export TURSO_REMOTE_ENCRYPTION_KEY="encryption key in base 64 encoded format"
//	go run main.go
//
// The encryption key must be encoded in base64 format.
package main

import (
	"database/sql"
	"fmt"
	"os"
	"time"

	_ "github.com/tursodatabase/go-libsql"
)

func main() {
	if err := run(); err != nil {
		fmt.Fprintf(os.Stderr, "error running example: %v\n", err)
		os.Exit(1)
	}
}

func run() (err error) {
	// Get database URL and auth token from environment variables
	dbUrl := os.Getenv("TURSO_URL")
	if dbUrl == "" {
		return fmt.Errorf("TURSO_URL environment variable not set")
	}

	sep := "?"
	authToken := os.Getenv("TURSO_AUTH_TOKEN")
	if authToken != "" {
		dbUrl += sep + "authToken=" + authToken
		sep = "&"
	}

	remoteEncryptionKey := os.Getenv("TURSO_REMOTE_ENCRYPTION_KEY")
	if remoteEncryptionKey != "" {
		dbUrl += sep + "remoteEncryptionKey=" + remoteEncryptionKey
	}

	// Open database connection
	db, err := sql.Open("libsql", dbUrl)
	if err != nil {
		return fmt.Errorf("error opening cloud db: %w", err)
	}
	defer db.Close()

	// Configure connection pool
	db.SetConnMaxIdleTime(9 * time.Second)

	// Create test table
	_, err = db.Exec("CREATE TABLE IF NOT EXISTS test (id INTEGER PRIMARY KEY, name TEXT)")
	if err != nil {
		return fmt.Errorf("error creating table: %w", err)
	}

	// Check if test data already exists
	var exists bool
	err = db.QueryRow("SELECT EXISTS(SELECT 1 FROM test WHERE id = 1)").Scan(&exists)
	if err != nil {
		return fmt.Errorf("error checking existing data: %w", err)
	}

	// Insert test data only if it doesn't exist
	if !exists {
		_, err = db.Exec("INSERT INTO test (id, name) VALUES (?, ?)", 1, "remote test")
		if err != nil {
			return fmt.Errorf("error inserting data: %w", err)
		}
		fmt.Println("Inserted test data")
	} else {
		fmt.Println("Test data already exists, skipping insert")
	}

	// Query the data
	rows, err := db.Query("SELECT * FROM test")
	if err != nil {
		return fmt.Errorf("error querying data: %w", err)
	}
	defer rows.Close()

	// Print results
	for rows.Next() {
		var id int
		var name string
		if err := rows.Scan(&id, &name); err != nil {
			return fmt.Errorf("error scanning row: %w", err)
		}
		fmt.Printf("Row: id=%d, name=%s\n", id, name)
	}
	if err := rows.Err(); err != nil {
		return fmt.Errorf("error iterating rows: %w", err)
	}

	fmt.Printf("Successfully connected and executed queries on %s\n", dbUrl)
	return nil
}

전체 예제 코드는 저장소에서 직접 확인하세요.

더 알아보기 (Learn more)

예제 코드 전체는 go-libsql 저장소에서 확인하세요: https://github.com/tursodatabase/go-libsql/tree/main/example (공식 문서 안내 페이지: https://docs.turso.tech/sdk/go/examples)