Skip to content

Add NewSyncedDatabaseConnector #64

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
May 28, 2025
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 46 additions & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
name: Test

on:
push:
branches: [ main ]
pull_request:
branches: [ main ]

jobs:
test:
strategy:
matrix:
go-version: [ '1.20' ]
os: [ubuntu-latest, macos-latest]
libsql-server-release: [libsql-server-v0.24.32]
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v3
- name: Set up Go
uses: actions/setup-go@v3
with:
go-version: ${{ matrix.go-version }}

- name: Install sqld
run: |
curl --proto '=https' --tlsv1.2 -LsSf https://github.com/tursodatabase/libsql/releases/download/${{ matrix.libsql-server-release }}/libsql-server-installer.sh | sh
echo "$HOME/.sqld/bin" >> $GITHUB_PATH
sqld --version

- name: Start sqld server
run: |
sqld &
while ! curl -s http://localhost:8080/health > /dev/null; do
echo "Waiting for sqld..."
sleep 1
done
echo "sqld is ready!"

- name: Build
run: go build -v ./...

- name: Test
env:
LIBSQL_PRIMARY_URL: "http://localhost:8080"
LIBSQL_AUTH_TOKEN: ""
run: go test -v ./...
3 changes: 3 additions & 0 deletions lib/include/libsql.h
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ typedef struct {
const char *encryption_key;
int sync_interval;
char with_webpki;
char offline;
} libsql_config;

typedef const libsql_connection *libsql_connection_t;
Expand All @@ -61,6 +62,8 @@ typedef struct {
extern "C" {
#endif // __cplusplus

int libsql_enable_internal_tracing(void);

int libsql_sync(libsql_database_t db, const char **out_err_msg);

int libsql_sync2(libsql_database_t db, replicated *out_replicated, const char **out_err_msg);
Expand Down
59 changes: 52 additions & 7 deletions libsql.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ type Option interface {
type option func(*config) error

type Replicated struct {
FrameNo int
FrameNo int
FramesSynced int
}

Expand Down Expand Up @@ -135,7 +135,37 @@ func NewEmbeddedReplicaConnector(dbPath string, primaryUrl string, opts ...Optio
if config.syncInterval != nil {
syncInterval = *config.syncInterval
}
return openEmbeddedReplicaConnector(dbPath, primaryUrl, authToken, readYourWrites, encryptionKey, syncInterval)
return openSyncConnector(dbPath, primaryUrl, authToken, readYourWrites, encryptionKey, syncInterval, false)
}

Copy link
Preview

Copilot AI May 28, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[nitpick] Add a Go doc comment for NewSyncedDatabaseConnector explaining its parameters, behavior, and how the offline flag differs from NewEmbeddedReplicaConnector.

Suggested change
// NewSyncedDatabaseConnector creates a Connector for a synchronized database.
//
// Parameters:
// - dbPath: The file path to the local database.
// - primaryUrl: The URL of the primary database to synchronize with.
// - opts: A variadic list of options to configure the connector (e.g., encryption key, sync interval).
//
// Behavior:
// This function initializes a Connector that synchronizes the local database with a primary database.
// It applies the provided options to configure the connector. If any errors occur during option application,
// they are aggregated and returned.
//
// Difference from NewEmbeddedReplicaConnector:
// The `offline` flag passed to `openSyncConnector` is set to `true` in this function, indicating that
// the connector operates in synchronized mode. In contrast, `NewEmbeddedReplicaConnector` sets the `offline`
// flag to `false`, indicating embedded replica mode.

Copilot uses AI. Check for mistakes.

func NewSyncedDatabaseConnector(dbPath string, primaryUrl string, opts ...Option) (*Connector, error) {
var config config
errs := make([]error, 0, len(opts))
for _, opt := range opts {
if err := opt.apply(&config); err != nil {
errs = append(errs, err)
}
}
if len(errs) > 0 {
return nil, errors.Join(errs...)
}
authToken := ""
if config.authToken != nil {
authToken = *config.authToken
}
readYourWrites := true
if config.readYourWrites != nil {
readYourWrites = *config.readYourWrites
}
encryptionKey := ""
if config.encryptionKey != nil {
encryptionKey = *config.encryptionKey
}
syncInterval := time.Duration(0)
if config.syncInterval != nil {
syncInterval = *config.syncInterval
}
return openSyncConnector(dbPath, primaryUrl, authToken, readYourWrites, encryptionKey, syncInterval, true)
}

type driver struct{}
Expand Down Expand Up @@ -173,7 +203,7 @@ func (d driver) OpenConnector(dbAddress string) (sqldriver.Connector, error) {

func libsqlSync(nativeDbPtr C.libsql_database_t) (Replicated, error) {
var errMsg *C.char
var rep C.replicated;
var rep C.replicated
statusCode := C.libsql_sync2(nativeDbPtr, &rep, &errMsg)
if statusCode != 0 {
return Replicated{0, 0}, libsqlError("failed to sync database ", statusCode, errMsg)
Expand All @@ -198,10 +228,10 @@ func openRemoteConnector(primaryUrl, authToken string) (*Connector, error) {
return &Connector{nativeDbPtr: nativeDbPtr}, nil
}

func openEmbeddedReplicaConnector(dbPath, primaryUrl, authToken string, readYourWrites bool, encryptionKey string, syncInterval time.Duration) (*Connector, error) {
func openSyncConnector(dbPath, primaryUrl, authToken string, readYourWrites bool, encryptionKey string, syncInterval time.Duration, offline bool) (*Connector, error) {
var closeCh chan struct{}
var closeAckCh chan struct{}
nativeDbPtr, err := libsqlOpenWithSync(dbPath, primaryUrl, authToken, readYourWrites, encryptionKey)
nativeDbPtr, err := libsqlOpenWithSync(dbPath, primaryUrl, authToken, readYourWrites, encryptionKey, offline)
if err != nil {
return nil, err
}
Expand Down Expand Up @@ -309,7 +339,7 @@ func libsqlOpenRemote(url, authToken string) (C.libsql_database_t, error) {
return db, nil
}

func libsqlOpenWithSync(dbPath, primaryUrl, authToken string, readYourWrites bool, encryptionKey string) (C.libsql_database_t, error) {
func libsqlOpenWithSync(dbPath, primaryUrl, authToken string, readYourWrites bool, encryptionKey string, offline bool) (C.libsql_database_t, error) {
dbPathNativeString := C.CString(dbPath)
defer C.free(unsafe.Pointer(dbPathNativeString))
primaryUrlNativeString := C.CString(primaryUrl)
Expand All @@ -321,15 +351,30 @@ func libsqlOpenWithSync(dbPath, primaryUrl, authToken string, readYourWrites boo
if readYourWrites {
readYourWritesNative = 1
}

var offlineNative C.char = 0
if offline {
offlineNative = 1
}

var encrytionKeyNativeString *C.char
if encryptionKey != "" {
encrytionKeyNativeString = C.CString(encryptionKey)
defer C.free(unsafe.Pointer(encrytionKeyNativeString))
}

config := C.libsql_config{
db_path: dbPathNativeString,
auth_token: authTokenNativeString,
primary_url: primaryUrlNativeString,
read_your_writes: readYourWritesNative,
encryption_key: encrytionKeyNativeString,
offline: offlineNative,
}

var db C.libsql_database_t
var errMsg *C.char
statusCode := C.libsql_open_sync(dbPathNativeString, primaryUrlNativeString, authTokenNativeString, readYourWritesNative, encrytionKeyNativeString, &db, &errMsg)
statusCode := C.libsql_open_sync_with_config(config, &db, &errMsg)
if statusCode != 0 {
return nil, libsqlError(fmt.Sprintf("failed to open database %s %s", dbPath, primaryUrl), statusCode, errMsg)
}
Expand Down