or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

callbacks.mdclustering.mdconfiguration.mdconnections.mderrors.mdindex.mdpooling.mdqueries.mdtypes.md

connections.mddocs/

0

# Connection Management

1

2

Core database connection functionality for establishing, managing, and executing queries on individual database connections. The MariaDB connector provides both Promise-based and callback-based APIs for maximum flexibility.

3

4

## Capabilities

5

6

### Create Connection

7

8

Creates a new database connection with the specified configuration.

9

10

```typescript { .api }

11

/**

12

* Create a new database connection (Promise-based API)

13

* @param config - Connection configuration object or connection string

14

* @returns Promise resolving to Connection instance

15

*/

16

function createConnection(config: string | ConnectionConfig): Promise<Connection>;

17

```

18

19

**Usage Example:**

20

21

```typescript

22

import mariadb from "mariadb";

23

24

// Using configuration object

25

const connection = await mariadb.createConnection({

26

host: "localhost",

27

user: "root",

28

password: "password",

29

database: "test",

30

port: 3306

31

});

32

33

// Using connection string

34

const connection2 = await mariadb.createConnection("mariadb://user:password@localhost:3306/database");

35

```

36

37

### Connection Interface (Promise-based)

38

39

Main connection interface providing Promise-based database operations.

40

41

```typescript { .api }

42

interface Connection extends EventEmitter {

43

/** Connection information */

44

info: ConnectionInfo | null;

45

/** Connection thread identifier */

46

readonly threadId: number | null;

47

48

/** Change connection user and reset session */

49

changeUser(options?: UserConnectionConfig): Promise<void>;

50

51

/** Execute SQL query using text protocol */

52

query<T = any>(sql: string | QueryOptions, values?: any): Promise<T>;

53

54

/** Execute SQL query using binary (prepared statement) protocol */

55

execute<T = any>(sql: string | QueryOptions, values?: any): Promise<T>;

56

57

/** Prepare SQL statement for repeated execution */

58

prepare(sql: string | QueryOptions): Promise<Prepare>;

59

60

/** Execute batch operations with multiple value sets */

61

batch<T = UpsertResult | UpsertResult[]>(sql: string | QueryOptions, values?: any): Promise<T>;

62

63

/** Execute query returning a Readable stream for large result sets */

64

queryStream(sql: string | QueryOptions, values?: any): Readable;

65

66

/** Start database transaction */

67

beginTransaction(): Promise<void>;

68

69

/** Commit current transaction */

70

commit(): Promise<void>;

71

72

/** Rollback current transaction */

73

rollback(): Promise<void>;

74

75

/** Send ping to ensure connection is active */

76

ping(): Promise<void>;

77

78

/** Reset connection state (rollback transactions, reset variables) */

79

reset(): Promise<void>;

80

81

/** Import SQL file into database */

82

importFile(config: SqlImportOptions): Promise<void>;

83

84

/** Check if connection is valid and active */

85

isValid(): boolean;

86

87

/** Close connection gracefully */

88

end(): Promise<void>;

89

90

/** Alias for end() */

91

close(): Promise<void>;

92

93

/** Force close connection immediately */

94

destroy(): void;

95

96

/** Pause connection (stop reading from socket) */

97

pause(): void;

98

99

/** Resume connection (continue reading from socket) */

100

resume(): void;

101

102

/** Get server version string */

103

serverVersion(): string;

104

105

/** Toggle debug mode */

106

debug(value: boolean): void;

107

108

/** Toggle compression debug mode */

109

debugCompress(value: boolean): void;

110

111

/** Escape SQL parameter to prevent injection */

112

escape(value: any): string;

113

114

/** Escape SQL identifier (table/column names) */

115

escapeId(identifier: string): string;

116

117

/** Event listeners */

118

on(event: 'end', listener: () => void): Connection;

119

on(event: 'error', listener: (err: SqlError) => void): Connection;

120

on(event: string | symbol, listener: (...args: any[]) => void): this;

121

}

122

```

123

124

### Connection Interface (Callback-based)

125

126

Alternative callback-based connection interface for applications preferring callback patterns.

127

128

```typescript { .api }

129

/**

130

* Create callback-based connection

131

* @param config - Connection configuration

132

* @returns Connection instance with callback methods

133

*/

134

function createConnection(config: string | ConnectionConfig): Connection;

135

136

interface Connection extends EventEmitter {

137

info: ConnectionInfo | null;

138

readonly threadId: number | null;

139

140

/** All methods use Node.js callback pattern: (error, result) => void */

141

changeUser(options: UserConnectionConfig, callback: (err: SqlError | null) => void): void;

142

query<T>(sql: string | QueryOptions, values: any, callback: (err: SqlError | null, result?: T, meta?: FieldInfo[]) => void): void;

143

query<T>(sql: string | QueryOptions, callback: (err: SqlError | null, result?: T, meta?: FieldInfo[]) => void): void;

144

execute<T>(sql: string | QueryOptions, values: any, callback: (err: SqlError | null, result?: T, meta?: FieldInfo[]) => void): void;

145

execute<T>(sql: string | QueryOptions, callback: (err: SqlError | null, result?: T, meta?: FieldInfo[]) => void): void;

146

prepare(sql: string | QueryOptions, callback: (err: SqlError | null, prepare?: Prepare) => void): void;

147

batch<T>(sql: string | QueryOptions, values: any, callback: (err: SqlError | null, result?: T) => void): void;

148

beginTransaction(callback: (err: SqlError | null) => void): void;

149

commit(callback: (err: SqlError | null) => void): void;

150

rollback(callback: (err: SqlError | null) => void): void;

151

ping(callback: (err: SqlError | null) => void): void;

152

reset(callback: (err: SqlError | null) => void): void;

153

importFile(config: SqlImportOptions, callback: (err: SqlError | null) => void): void;

154

end(callback: (err: SqlError | null) => void): void;

155

close(callback: (err: SqlError | null) => void): void;

156

157

/** Synchronous methods remain the same */

158

isValid(): boolean;

159

destroy(): void;

160

pause(): void;

161

resume(): void;

162

serverVersion(): string;

163

debug(value: boolean): void;

164

debugCompress(value: boolean): void;

165

escape(value: any): string;

166

escapeId(identifier: string): string;

167

}

168

```

169

170

### User Configuration

171

172

Configuration options for changing user credentials during connection lifetime.

173

174

```typescript { .api }

175

interface UserConnectionConfig {

176

/** Name of the database to use */

177

database?: string;

178

/** Connection attributes sent to server */

179

connectAttributes?: any;

180

/** Protocol character set (default: 'UTF8MB4') */

181

charset?: string;

182

/** Connection collation (default: 'UTF8MB4_UNICODE_CI') */

183

collation?: string;

184

/** MySQL user to authenticate as */

185

user?: string;

186

/** Password for MySQL user */

187

password?: string;

188

}

189

```

190

191

### SQL File Import

192

193

Import SQL files directly into the database. The connector supports both standalone import (creates its own connection) and import through existing connections.

194

195

```typescript { .api }

196

/**

197

* Import SQL file using standalone function (Promise-based)

198

* @param config - Import configuration including connection details

199

* @returns Promise that resolves when import completes

200

*/

201

function importFile(config: ImportFileConfig): Promise<void>;

202

203

/**

204

* Import SQL file using standalone function (Callback-based)

205

* @param config - Import configuration including connection details

206

* @param callback - Callback function (err) => void

207

*/

208

function importFile(config: ImportFileConfig, callback: (err: SqlError | null) => void): void;

209

210

interface ImportFileConfig extends ConnectionConfig {

211

/** Path to SQL file to import */

212

file: string;

213

}

214

215

interface SqlImportOptions {

216

/** Path to SQL file */

217

file: string;

218

/** Target database name (optional, uses current if not specified) */

219

database?: string;

220

}

221

```

222

223

**Usage Examples:**

224

225

```javascript

226

const mariadb = require("mariadb");

227

228

// Promise-based standalone import

229

await mariadb.importFile({

230

host: "localhost",

231

user: "root",

232

password: "password",

233

database: "test",

234

file: "./backup.sql"

235

});

236

237

// Callback-based standalone import

238

const mariadbCallback = require("mariadb/callback");

239

mariadbCallback.importFile({

240

host: "localhost",

241

user: "root",

242

password: "password",

243

database: "test",

244

file: "./schema.sql"

245

}, (err) => {

246

if (err) {

247

console.error('Import failed:', err);

248

return;

249

}

250

console.log('SQL file imported successfully');

251

});

252

253

// Import using existing connection (Promise-based)

254

const connection = await mariadb.createConnection({

255

host: "localhost",

256

user: "root",

257

password: "password",

258

database: "test"

259

});

260

261

await connection.importFile({

262

file: "./schema.sql",

263

database: "production" // Optional: import to different database

264

});

265

266

// Import using existing connection (Callback-based)

267

const callbackConnection = mariadbCallback.createConnection({

268

host: "localhost",

269

user: "root",

270

password: "password",

271

database: "test"

272

});

273

274

callbackConnection.on('connect', () => {

275

callbackConnection.importFile({

276

file: "./data.sql"

277

}, (err) => {

278

if (err) {

279

console.error('Import error:', err);

280

return;

281

}

282

console.log('Import completed');

283

});

284

});

285

```

286

287

### Connection Events

288

289

Connections emit various events during their lifecycle.

290

291

```typescript { .api }

292

// Connection established (callback API only)

293

connection.on('connect', () => {

294

console.log('Connected to database');

295

});

296

297

// Connection ended

298

connection.on('end', () => {

299

console.log('Connection closed');

300

});

301

302

// Connection error

303

connection.on('error', (err: SqlError) => {

304

console.error('Connection error:', err);

305

});

306

```

307

308

### Default Options

309

310

Get default connection configuration options.

311

312

```typescript { .api }

313

/**

314

* Get default connection options

315

* @param opts - Optional configuration to override defaults

316

* @returns Object containing default options

317

*/

318

function defaultOptions(opts?: ConnectionConfig): any;

319

```

320

321

**Usage Example:**

322

323

```typescript

324

const defaults = mariadb.defaultOptions();

325

console.log(defaults.host); // 'localhost'

326

console.log(defaults.port); // 3306

327

328

// Override specific options

329

const customDefaults = mariadb.defaultOptions({

330

host: "myserver.com",

331

timeout: 5000

332

});

333

```