or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

client-configuration.mddatabase-operations.mdindex.mdtransaction-management.md
tile.json

index.mddocs/

0

# libSQL Client

1

2

libSQL Client is a comprehensive TypeScript/JavaScript driver for libSQL databases, offering both local and remote database connectivity with advanced features like embedded replicas that can work offline and sync with remote Turso databases. It provides full SQLite compatibility with additional libSQL features like encryption at rest and AI & Vector Search capabilities for modern applications.

3

4

## Package Information

5

6

- **Package Name**: @libsql/client

7

- **Package Type**: npm

8

- **Language**: TypeScript

9

- **Installation**: `npm install @libsql/client`

10

11

## Core Imports

12

13

```typescript

14

import { createClient } from "@libsql/client";

15

```

16

17

For CommonJS:

18

19

```javascript

20

const { createClient } = require("@libsql/client");

21

```

22

23

Platform-specific imports:

24

25

```typescript

26

// Node.js optimized

27

import { createClient } from "@libsql/client/node";

28

29

// HTTP-only client

30

import { createClient } from "@libsql/client/http";

31

32

// WebSocket-only client

33

import { createClient } from "@libsql/client/ws";

34

35

// Local SQLite3 client

36

import { createClient } from "@libsql/client/sqlite3";

37

38

// Web/browser client

39

import { createClient } from "@libsql/client/web";

40

```

41

42

## Basic Usage

43

44

```typescript

45

import { createClient } from "@libsql/client";

46

47

// Create client for local database

48

const client = createClient({

49

url: "file:local.db"

50

});

51

52

// Create client for remote database

53

const client = createClient({

54

url: "libsql://your-database.turso.io",

55

authToken: "your-auth-token"

56

});

57

58

// Create embedded replica (works offline, syncs with remote)

59

const client = createClient({

60

url: "file:local.db",

61

syncUrl: "libsql://your-database.turso.io",

62

authToken: "your-auth-token",

63

syncInterval: 60000 // sync every minute

64

});

65

66

// Execute a simple query

67

const result = await client.execute("SELECT * FROM users");

68

console.log(result.rows);

69

70

// Execute with parameters

71

const user = await client.execute({

72

sql: "SELECT * FROM users WHERE id = ?",

73

args: [1]

74

});

75

76

// Execute a batch of statements in a transaction

77

const results = await client.batch([

78

"CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT)",

79

{

80

sql: "INSERT INTO users (name) VALUES (?)",

81

args: ["Alice"]

82

}

83

], "write");

84

85

// Don't forget to close when done

86

client.close();

87

```

88

89

## Architecture

90

91

libSQL Client is built around several key components:

92

93

- **Multi-Protocol Support**: Automatic selection between HTTP, WebSocket, and local SQLite based on URL scheme

94

- **Client Implementations**: Platform-specific clients (`HttpClient`, `WsClient`, `Sqlite3Client`) behind unified interface

95

- **Embedded Replicas**: Local SQLite files that can sync with remote Turso databases for offline capability

96

- **Transaction Support**: Both batch (non-interactive) and interactive transaction modes

97

- **Type Safety**: Full TypeScript support with configurable integer representation modes

98

- **Connection Management**: Automatic connection pooling, reconnection, and concurrency control

99

- **Cross-Platform**: Supports Node.js, browsers, Deno, Cloudflare Workers, and other runtimes

100

101

## Capabilities

102

103

### Client Creation and Configuration

104

105

Core client creation with comprehensive configuration options for different deployment scenarios and database connection types.

106

107

```typescript { .api }

108

function createClient(config: Config): Client;

109

110

interface Config {

111

url: string;

112

authToken?: string;

113

encryptionKey?: string;

114

syncUrl?: string;

115

syncInterval?: number;

116

readYourWrites?: boolean;

117

offline?: boolean;

118

tls?: boolean;

119

intMode?: IntMode;

120

fetch?: Function;

121

concurrency?: number | undefined;

122

}

123

124

type IntMode = "number" | "bigint" | "string";

125

```

126

127

[Client Configuration](./client-configuration.md)

128

129

### Database Operations

130

131

Core database interaction methods for executing SQL statements, managing results, and handling different query patterns.

132

133

```typescript { .api }

134

interface Client {

135

execute(stmt: InStatement): Promise<ResultSet>;

136

execute(sql: string, args?: InArgs): Promise<ResultSet>;

137

batch(stmts: Array<InStatement | [string, InArgs?]>, mode?: TransactionMode): Promise<Array<ResultSet>>;

138

migrate(stmts: Array<InStatement>): Promise<Array<ResultSet>>;

139

transaction(mode?: TransactionMode): Promise<Transaction>;

140

/** @deprecated Please specify the `mode` explicitly. The default `"write"` will be removed in the next major release. */

141

transaction(): Promise<Transaction>;

142

executeMultiple(sql: string): Promise<void>;

143

sync(): Promise<Replicated>;

144

close(): void;

145

reconnect(): void;

146

closed: boolean;

147

protocol: string;

148

}

149

150

interface ResultSet {

151

columns: Array<string>;

152

columnTypes: Array<string>;

153

rows: Array<Row>;

154

rowsAffected: number;

155

lastInsertRowid: bigint | undefined;

156

toJSON(): any;

157

}

158

```

159

160

[Database Operations](./database-operations.md)

161

162

### Transaction Management

163

164

Interactive transaction support with commit/rollback control for complex multi-statement operations requiring atomicity.

165

166

```typescript { .api }

167

interface Transaction {

168

execute(stmt: InStatement): Promise<ResultSet>;

169

batch(stmts: Array<InStatement>): Promise<Array<ResultSet>>;

170

executeMultiple(sql: string): Promise<void>;

171

rollback(): Promise<void>;

172

commit(): Promise<void>;

173

close(): void;

174

closed: boolean;

175

}

176

177

type TransactionMode = "write" | "read" | "deferred";

178

```

179

180

[Transaction Management](./transaction-management.md)

181

182

## Core Types

183

184

```typescript { .api }

185

type Value = null | string | number | bigint | ArrayBuffer;

186

187

type InValue = Value | boolean | Uint8Array | Date;

188

189

type InStatement = { sql: string; args?: InArgs } | string;

190

191

type InArgs = Array<InValue> | Record<string, InValue>;

192

193

interface Row {

194

length: number;

195

[index: number]: Value;

196

[name: string]: Value;

197

}

198

199

type Replicated = { frame_no: number; frames_synced: number } | undefined;

200

201

class LibsqlError extends Error {

202

code: string;

203

rawCode?: number;

204

constructor(message: string, code: string, rawCode?: number, cause?: Error);

205

}

206

```

207

208

## Platform-Specific Behavior

209

210

### Client Implementation Selection

211

212

libSQL Client automatically selects the appropriate implementation based on URL scheme:

213

214

- **`file:` URLs**`Sqlite3Client` (Node.js only)

215

- **`http:`/`https:` URLs**`HttpClient` (all platforms)

216

- **`ws:`/`wss:` URLs**`WsClient` (where WebSockets supported)

217

- **`libsql:` URLs** → Auto-detection (prefers WebSocket, falls back to HTTP)

218

219

### Feature Availability by Platform

220

221

**Node.js Environment:**

222

- ✅ All features supported including local SQLite files and encryption

223

- ✅ Embedded replicas with full sync capabilities

224

- ✅ WebSocket and HTTP connections

225

226

**Browser/Web Environment:**

227

- ✅ HTTP and WebSocket connections to remote databases

228

- ❌ Local file access and embedded replicas not supported

229

- ❌ Encryption keys not supported (use remote encrypted databases)

230

231

**Deno/Cloudflare Workers:**

232

- ✅ HTTP connections with custom fetch support

233

- ✅ WebSocket connections (where runtime supports it)

234

- ❌ Local SQLite files not supported

235

236

### Sync Operation Limitations

237

238

The `sync()` method is only available for embedded replica configurations:

239

- Requires both `url` (local file) and `syncUrl` (remote database)

240

- Only works with `Sqlite3Client` (Node.js environment)

241

- Returns `undefined` for non-replica clients

242

243

### Integer Mode Considerations

244

245

**`"number"` mode (default):**

246

- Safe for integers up to 2^53-1 (9,007,199,254,740,991)

247

- Throws `RangeError` for larger values

248

- Best performance for typical use cases

249

250

**`"bigint"` mode:**

251

- Handles arbitrary precision integers

252

- Requires explicit `BigInt()` conversion in calculations

253

- Recommended for applications with large integer values

254

255

**`"string"` mode:**

256

- Always safe but requires manual parsing

257

- Useful for preserving exact precision in display