golang基于Google Sheets的简单数据库抽象层插件库GoFreeDB的使用

GoFreeDB - 基于Google Sheets的简单数据库抽象层插件库

概述

GoFreeDB是一个Golang库,它在Google Sheets之上提供了常见且简单的数据库抽象层。

GoFreeDB Logo

更快地用Google Sheets作为数据库交付!

特性

  1. 在Google Sheets之上提供简单的键值基于行的数据库接口
  2. 无需任何服务器设置即可服务您的数据(通过利用Google Sheets基础设施)
  3. 支持足够灵活的查询语言来执行各种数据查询
  4. 通过熟悉的Google Sheets UI手动操作数据(无需管理页面)

安装

go get github.com/FreeLeh/GoFreeDB

前提条件

  1. 获取Google OAuth2服务账户凭据
  2. 准备一个Google Sheets电子表格用于存储数据

行存储(Row Store)示例

假设表中的每一行都由Person结构体表示:

type Person struct {
    Name string `db:"name"`
    Age  int    `db:"age"`
}

初始化行存储:

import (
    "github.com/FreeLeh/GoFreeDB"
    "github.com/FreeLeh/GoFreeDB/google/auth"
)

// 使用Google服务账户
auth, err := auth.NewServiceFromFile(
    "<path_to_service_account_json>", 
    freedb.FreeDBGoogleAuthScopes, 
    auth.ServiceConfig{},
)

// 使用Google OAuth2流程
auth, err := auth.NewOAuth2FromFile(
    "<path_to_client_secret_json>", 
    "<path_to_cached_credentials_json>", 
    freedb.FreeDBGoogleAuthScopes, 
    auth.OAuth2Config{},
)

store := freedb.NewGoogleSheetRowStore(
    auth, 
    "<spreadsheet_id>", 
    "<sheet_name>", 
    freedb.GoogleSheetRowStoreConfig{Columns: []string{"name", "age"}},
)
defer store.Close(context.Background())

查询行

// 输出变量
var output []Person

// 查询所有行的所有列
err := store.
    Select(&output).
    Exec(context.Background())

// 查询所有行的部分列(未选中的结构体字段将有默认值)
err := store.
    Select(&output, "name").
    Exec(context.Background())

// 带条件的查询
err := store.
    Select(&output).
    Where("name = ? OR age >= ?", "freedb", 10).
    Exec(context.Background())

// 带排序的查询
ordering := []freedb.ColumnOrderBy{
    {Column: "name", OrderBy: freedb.OrderByAsc},
    {Column: "age", OrderBy: freedb.OrderByDesc},
}
err := store.
    Select(&output).
    OrderBy(ordering).
    Exec(context.Background())

// 带偏移和限制的查询
err := store.
    Select(&output).
    Offset(10).
    Limit(20).
    Exec(context.Background())

插入行

err := store.Insert(
    Person{Name: "no_pointer", Age: 10}, 
    &Person{Name: "with_pointer", Age: 20},
).Exec(context.Background())

更新行

colToUpdate := make(map[string]interface{})
colToUpdate["name"] = "new_name"
colToUpdate["age"] = 12

// 更新所有行
err := store.
    Update(colToUpdate).
    Exec(context.Background())

// 带条件的更新
err := store.
    Update(colToUpdate).
    Where("name = ? OR age >= ?", "freedb", 10).
    Exec(context.Background())

删除行

// 删除所有行
err := store.
    Delete().
    Exec(context.Background())

// 带条件的删除
err := store.
    Delete().
    Where("name = ? OR age >= ?", "freedb", 10).
    Exec(context.Background())

键值存储(KV Store)示例

import (
    "github.com/FreeLeh/GoFreeDB"
    "github.com/FreeLeh/GoFreeDB/google/auth"
)

// 初始化认证...

kv := freedb.NewGoogleSheetKVStore(
    auth, 
    "<spreadsheet_id>", 
    "<sheet_name>", 
    freedb.GoogleSheetKVStoreConfig{Mode: freedb.KVSetModeAppendOnly},
)
defer kv.Close(context.Background())

基本操作

// 获取值
value, err := kv.Get(context.Background(), "k1")

// 设置键值
err := kv.Set(context.Background(), "k1", []byte("some_value"))

// 删除键
err := kv.Delete(context.Background(), "k1")

键值存储V2(KV Store V2)示例

KV Store V2在内部使用行存储实现,是更推荐的版本。

kv := freedb.NewGoogleSheetKVStoreV2(
    auth, 
    "<spreadsheet_id>", 
    "<sheet_name>", 
    freedb.GoogleSheetKVStoreV2Config{Mode: freedb.KVSetModeAppendOnly},
)
defer kv.Close(context.Background())

基本操作

// 获取值
value, err := kv.Get(context.Background(), "k1")

// 设置键值
err := kv.Set(context.Background(), "k1", []byte("some_value"))

// 删除键
err := kv.Delete(context.Background(), "k1")

结构体字段到列的映射

db结构体标签可用于定义结构体字段和列名之间的映射,类似于encoding/json中的json标签。

如果没有db标签,库将直接使用字段名(区分大小写)。

// 这将映射到确切的列名"Name"和"Age"
type NoTagPerson struct {
    Name string
    Age  int
}

// 这将映射到确切的列名"name"和"age"
type WithTagPerson struct {
    Name string  `db:"name"`
    Age  int     `db:"age"`
}

许可证

该项目采用MIT许可证


更多关于golang基于Google Sheets的简单数据库抽象层插件库GoFreeDB的使用的实战教程也可以访问 https://www.itying.com/category-94-b0.html

1 回复

更多关于golang基于Google Sheets的简单数据库抽象层插件库GoFreeDB的使用的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


GoFreeDB: 基于Google Sheets的Golang数据库抽象层

GoFreeDB是一个轻量级的Golang库,它将Google Sheets作为简单的数据库后端,为开发者提供了一个方便的抽象层。下面我将详细介绍如何使用这个库。

安装

首先安装GoFreeDB库:

go get github.com/yaa110/gofreedb

基本使用

1. 初始化连接

package main

import (
	"context"
	"fmt"
	"log"

	"github.com/yaa110/gofreedb"
	"golang.org/x/oauth2/google"
)

func main() {
	// 1. 准备Google Sheets API凭据
	credential, err := google.CredentialsFromJSON(
		context.Background(),
		[]byte(`你的Google API JSON凭据`),
		"https://www.googleapis.com/auth/spreadsheets",
	)
	if err != nil {
		log.Fatalf("无法加载凭据: %v", err)
	}

	// 2. 创建GoFreeDB客户端
	client := gofreedb.NewClient(credential)

	// 3. 连接到特定的Google Sheet
	sheetID := "你的Google Sheet ID" // 在URL中可以找到
	db, err := client.Connect(context.Background(), sheetID)
	if err != nil {
		log.Fatalf("连接失败: %v", err)
	}
	defer db.Close()

	// 现在可以使用db进行操作...
}

2. 定义模型

GoFreeDB使用结构体标签来映射到表格列:

type Product struct {
	ID       string `gofreedb:"id"`       // 主键列
	Name     string `gofreedb:"name"`     // 名称列
	Price    int    `gofreedb:"price"`    // 价格列
	Category string `gofreedb:"category"` // 分类列
}

3. CRUD操作

创建表

// 创建名为"products"的表,使用Product结构体作为模型
err = db.CreateTable(context.Background(), "products", Product{})
if err != nil {
    log.Fatalf("创建表失败: %v", err)
}

插入数据

newProduct := Product{
    ID:       "p001",
    Name:     "Laptop",
    Price:    999,
    Category: "Electronics",
}

// 插入单条记录
err = db.Insert(context.Background(), "products", newProduct)
if err != nil {
    log.Printf("插入失败: %v", err)
}

// 批量插入
products := []Product{
    {ID: "p002", Name: "Phone", Price: 699, Category: "Electronics"},
    {ID: "p003", Name: "Tablet", Price: 399, Category: "Electronics"},
}
err = db.InsertMany(context.Background(), "products", products)

查询数据

// 查询所有记录
var allProducts []Product
err = db.Find(context.Background(), "products", &allProducts)
if err != nil {
    log.Printf("查询失败: %v", err)
}
fmt.Printf("所有产品: %+v\n", allProducts)

// 带条件查询
var expensiveProducts []Product
err = db.FindWhere(context.Background(), "products", &expensiveProducts, "price > ?", 500)
if err != nil {
    log.Printf("条件查询失败: %v", err)
}
fmt.Printf("高价产品: %+v\n", expensiveProducts)

// 查询单条记录
var singleProduct Product
err = db.FindOne(context.Background(), "products", &singleProduct, "id = ?", "p001")
if err != nil {
    log.Printf("查询单条失败: %v", err)
}
fmt.Printf("单个产品: %+v\n", singleProduct)

更新数据

// 更新记录
updated := Product{
    ID:       "p001",
    Name:     "Premium Laptop",
    Price:    1299,
    Category: "Electronics",
}

err = db.Update(context.Background(), "products", updated, "id = ?", "p001")
if err != nil {
    log.Printf("更新失败: %v", err)
}

删除数据

// 删除记录
err = db.Delete(context.Background(), "products", "id = ?", "p003")
if err != nil {
    log.Printf("删除失败: %v", err)
}

高级功能

事务支持

err = db.Transaction(context.Background(), func(tx *gofreedb.Tx) error {
    // 在事务中执行多个操作
    if err := tx.Insert("products", Product{ID: "p004", Name: "Mouse", Price: 25}); err != nil {
        return err
    }
    
    if err := tx.Update("products", Product{ID: "p002", Price: 749}, "id = ?", "p002"); err != nil {
        return err
    }
    
    return nil
})

if err != nil {
    log.Printf("事务失败: %v", err)
}

自定义映射

如果你的Google Sheets列名与结构体字段名不同,可以使用gofreedb标签自定义映射:

type User struct {
    UserID    string `gofreedb:"user_id"`  // 映射到"user_id"列
    FullName  string `gofreedb:"name"`     // 映射到"name"列
    Email     string `gofreedb:"email"`    // 映射到"email"列
    IsActive  bool   `gofreedb:"active"`   // 映射到"active"列
}

注意事项

  1. Google Sheets API有速率限制,大量操作时需要考虑
  2. 不适合需要复杂查询或事务的高并发应用
  3. 每个工作表(Sheet)对应一个表(Table)
  4. 第一行默认作为列名行

GoFreeDB为简单的数据存储需求提供了一个便捷的解决方案,特别适合原型开发、小型应用或需要电子表格界面的场景。

回到顶部