or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

expressions.mdindex.mdsecurity.mdsql-parsing.mdutilities.md

utilities.mddocs/

0

# Utility Functions

1

2

Helper functions for SQL string manipulation, AST processing, and database-specific formatting. These utilities provide lower-level functionality for working with SQL structures and AST nodes.

3

4

## Core Utilities

5

6

### Value Expression Creation

7

8

Create AST nodes for literal values.

9

10

```javascript { .api }

11

/**

12

* Create value expression AST from JavaScript values

13

* @param value - JavaScript value to convert

14

* @returns ValueExpr AST node

15

*/

16

createValueExpr(value: any): ValueExpr;

17

18

interface ValueExpr<T = string | number | boolean> {

19

type: "string" | "number" | "boolean" | "bool" | "null" | "expr_list";

20

value: T;

21

}

22

```

23

24

**Usage Examples:**

25

26

```javascript

27

import { createValueExpr } from 'node-sql-parser/lib/util';

28

29

// Create different value types

30

const stringExpr = createValueExpr('hello');

31

console.log(stringExpr); // { type: 'string', value: 'hello' }

32

33

const numberExpr = createValueExpr(42);

34

console.log(numberExpr); // { type: 'number', value: 42 }

35

36

const boolExpr = createValueExpr(true);

37

console.log(boolExpr); // { type: 'bool', value: true }

38

39

const nullExpr = createValueExpr(null);

40

console.log(nullExpr); // { type: 'null', value: null }

41

42

// Array values create expression lists

43

const arrayExpr = createValueExpr([1, 2, 3]);

44

console.log(arrayExpr);

45

// { type: 'expr_list', value: [{ type: 'number', value: 1 }, ...] }

46

```

47

48

### Binary Expression Creation

49

50

Create AST nodes for binary operations.

51

52

```javascript { .api }

53

/**

54

* Create binary expression AST

55

* @param operator - Binary operator string

56

* @param left - Left operand

57

* @param right - Right operand

58

* @returns Binary expression AST node

59

*/

60

createBinaryExpr(operator: string, left: any, right: any): Binary;

61

62

interface Binary {

63

type: "binary_expr";

64

operator: string;

65

left: ExpressionValue | ExprList;

66

right: ExpressionValue | ExprList;

67

}

68

```

69

70

**Usage Examples:**

71

72

```javascript

73

import { createBinaryExpr, createValueExpr } from 'node-sql-parser/lib/util';

74

75

// Create comparison expression

76

const leftCol = { type: 'column_ref', table: null, column: 'age' };

77

const rightVal = createValueExpr(18);

78

const comparison = createBinaryExpr('>=', leftCol, rightVal);

79

80

console.log(comparison);

81

// {

82

// type: 'binary_expr',

83

// operator: '>=',

84

// left: { type: 'column_ref', table: null, column: 'age' },

85

// right: { type: 'number', value: 18 }

86

// }

87

88

// Create logical expression

89

const expr1 = createBinaryExpr('>', leftCol, createValueExpr(0));

90

const expr2 = createBinaryExpr('<', leftCol, createValueExpr(100));

91

const logicalExpr = createBinaryExpr('AND', expr1, expr2);

92

93

console.log(logicalExpr.operator); // 'AND'

94

```

95

96

### String Processing

97

98

Functions for handling SQL string literals and identifiers.

99

100

```javascript { .api }

101

/**

102

* Escape SQL string literal (currently returns input unchanged)

103

* @param str - String to escape

104

* @returns Escaped string

105

*/

106

escape(str: string): string;

107

108

/**

109

* Convert literal value to SQL string

110

* @param literal - Literal value to convert

111

* @returns SQL string representation

112

*/

113

literalToSQL(literal: any): string;

114

115

/**

116

* Convert identifier to SQL with proper quoting

117

* @param identifier - Identifier to convert

118

* @param isDual - Whether this is a dual table context

119

* @param surround - Custom surrounding characters

120

* @returns Quoted SQL identifier

121

*/

122

identifierToSql(identifier: string, isDual?: boolean, surround?: string): string;

123

124

/**

125

* Convert column identifier to SQL

126

* @param identifier - Column identifier to convert

127

* @returns Quoted SQL column identifier

128

*/

129

columnIdentifierToSql(identifier: string): string;

130

```

131

132

**Usage Examples:**

133

134

```javascript

135

import { escape, literalToSQL, identifierToSql, columnIdentifierToSql } from 'node-sql-parser/lib/util';

136

137

// String escaping (currently no-op)

138

const escaped = escape("O'Reilly");

139

console.log(escaped); // "O'Reilly"

140

141

// Literal conversion

142

const stringLiteral = literalToSQL({ type: 'string', value: 'hello' });

143

console.log(stringLiteral); // "'hello'"

144

145

const numberLiteral = literalToSQL({ type: 'number', value: 42 });

146

console.log(numberLiteral); // "42"

147

148

const boolLiteral = literalToSQL({ type: 'bool', value: true });

149

console.log(boolLiteral); // "TRUE"

150

151

// Identifier quoting (database-specific)

152

const mysqlId = identifierToSql("user_name");

153

console.log(mysqlId); // "`user_name`"

154

155

const columnId = columnIdentifierToSql("email_address");

156

console.log(columnId); // "`email_address`"

157

```

158

159

### Data Type Conversion

160

161

Convert data type definitions to SQL strings.

162

163

```javascript { .api }

164

/**

165

* Convert data type definition to SQL string

166

* @param expr - Data type object to convert

167

* @returns SQL data type string

168

*/

169

dataTypeToSQL(expr: DataType): string;

170

171

interface DataType {

172

dataType: string;

173

length?: number;

174

parentheses?: boolean;

175

scale?: number;

176

suffix?: string[];

177

}

178

```

179

180

**Usage Examples:**

181

182

```javascript

183

import { dataTypeToSQL } from 'node-sql-parser/lib/util';

184

185

// Basic data types

186

const varchar = dataTypeToSQL({ dataType: 'VARCHAR', length: 255, parentheses: true });

187

console.log(varchar); // "VARCHAR(255)"

188

189

const decimal = dataTypeToSQL({

190

dataType: 'DECIMAL',

191

length: 10,

192

scale: 2,

193

parentheses: true

194

});

195

console.log(decimal); // "DECIMAL(10, 2)"

196

197

// Data types with suffixes

198

const unsignedInt = dataTypeToSQL({

199

dataType: 'INT',

200

suffix: ['UNSIGNED']

201

});

202

console.log(unsignedInt); // "INT UNSIGNED"

203

```

204

205

### Parser Configuration

206

207

Functions for managing parser options and settings.

208

209

```javascript { .api }

210

/**

211

* Get current parser options

212

* @returns Current parser configuration

213

*/

214

getParserOpt(): Option;

215

216

/**

217

* Set parser options

218

* @param opt - Parser options to set

219

*/

220

setParserOpt(opt: Option): void;

221

222

/**

223

* Default parser options

224

*/

225

DEFAULT_OPT: Option;

226

227

interface Option {

228

database: string;

229

type: string;

230

trimQuery: boolean;

231

parseOptions: {

232

includeLocations: boolean;

233

};

234

}

235

```

236

237

**Usage Examples:**

238

239

```javascript

240

import { getParserOpt, setParserOpt, DEFAULT_OPT } from 'node-sql-parser/lib/util';

241

242

// Get current options

243

const currentOpt = getParserOpt();

244

console.log(currentOpt.database); // Current database setting

245

246

// Set new options

247

setParserOpt({

248

database: 'PostgreSQL',

249

type: 'table',

250

trimQuery: false,

251

parseOptions: { includeLocations: true }

252

});

253

254

// Access default options

255

console.log(DEFAULT_OPT);

256

// {

257

// database: 'mysql',

258

// type: 'table',

259

// trimQuery: true,

260

// parseOptions: { includeLocations: false }

261

// }

262

```

263

264

### Parameter Replacement

265

266

Replace parameter placeholders in AST with actual values.

267

268

```javascript { .api }

269

/**

270

* Replace parameters in AST with actual values

271

* @param ast - AST to process

272

* @param params - Parameter values to substitute

273

* @returns Modified AST with parameters replaced

274

*/

275

replaceParams(ast: AST, params: any): AST;

276

```

277

278

**Usage Examples:**

279

280

```javascript

281

import { Parser } from 'node-sql-parser';

282

import { replaceParams } from 'node-sql-parser/lib/util';

283

284

// Parse SQL with parameters

285

const parser = new Parser();

286

const ast = parser.astify('SELECT * FROM users WHERE id = :id AND status = :status');

287

288

// Replace parameters

289

const withParams = replaceParams(ast, {

290

id: 123,

291

status: 'active'

292

});

293

294

// Convert back to SQL

295

const sql = parser.sqlify(withParams);

296

console.log(sql); // "SELECT * FROM `users` WHERE `id` = 123 AND `status` = 'active'"

297

```

298

299

### Helper Functions

300

301

Utility functions for common operations.

302

303

```javascript { .api }

304

/**

305

* Check if value exists (truthy check)

306

* @param val - Value to check

307

* @returns True if value is truthy

308

*/

309

hasVal(val: any): boolean;

310

311

/**

312

* Convert string to uppercase if it exists

313

* @param val - String to convert

314

* @returns Uppercase string or undefined

315

*/

316

toUpper(val: string): string | undefined;

317

318

/**

319

* Connect keyword with string

320

* @param keyword - SQL keyword

321

* @param str - String to connect

322

* @returns Connected string or undefined

323

*/

324

connector(keyword: string, str: string): string | undefined;

325

326

/**

327

* Connect common options with keywords

328

* @param keyword - SQL keyword

329

* @param action - Action function

330

* @param opt - Options object

331

* @returns Connected string or undefined

332

*/

333

commonOptionConnector(keyword: string, action: Function, opt: any): string | undefined;

334

```

335

336

**Usage Examples:**

337

338

```javascript

339

import { hasVal, toUpper, connector, commonOptionConnector } from 'node-sql-parser/lib/util';

340

341

// Value checking

342

console.log(hasVal('hello')); // true

343

console.log(hasVal(null)); // false

344

console.log(hasVal('')); // false

345

346

// String operations

347

console.log(toUpper('select')); // "SELECT"

348

349

// Keyword connection

350

const orderClause = connector('ORDER BY', 'name ASC');

351

console.log(orderClause); // "ORDER BY name ASC"

352

353

// Option connection

354

const limitClause = commonOptionConnector(

355

'LIMIT',

356

(opt) => opt.count.toString(),

357

{ count: 10 }

358

);

359

console.log(limitClause); // "LIMIT 10"

360

```

361

362

## Specialized Utilities

363

364

### Comment Processing

365

366

Functions for handling SQL comments.

367

368

```javascript { .api }

369

/**

370

* Convert comment object to SQL string

371

* @param comment - Comment object to convert

372

* @returns SQL comment string

373

*/

374

commentToSQL(comment: KeywordComment): string;

375

376

interface KeywordComment {

377

type: "comment";

378

keyword: "comment";

379

symbol?: "=";

380

value: string;

381

}

382

```

383

384

### SQL Clause Utilities

385

386

Specialized functions for specific SQL clauses.

387

388

```javascript { .api }

389

/**

390

* Convert TOP clause to SQL (SQL Server)

391

* @param opt - TOP clause options

392

* @returns SQL TOP clause

393

*/

394

topToSQL(opt: TopOptions): string;

395

396

interface TopOptions {

397

value: number | string;

398

percent?: string;

399

parentheses?: boolean;

400

}

401

402

/**

403

* Convert AUTO_INCREMENT to SQL

404

* @param autoIncrement - Auto increment specification

405

* @returns SQL auto increment clause

406

*/

407

autoIncrementToSQL(autoIncrement: string | AutoIncrementOptions): string;

408

409

interface AutoIncrementOptions {

410

keyword: string;

411

seed: any;

412

increment: any;

413

parentheses?: boolean;

414

}

415

416

/**

417

* Convert RETURNING clause to SQL

418

* @param returning - RETURNING clause object

419

* @returns SQL RETURNING clause

420

*/

421

returningToSQL(returning: Returning): string;

422

423

interface Returning {

424

columns: any[];

425

}

426

427

/**

428

* Convert partitions specification to SQL

429

* @param expr - Partitions expression

430

* @returns SQL partitions clause

431

*/

432

onPartitionsToSQL(expr: PartitionsExpr): string;

433

434

interface PartitionsExpr {

435

type: string;

436

partitions: any[];

437

}

438

439

/**

440

* Convert trigger event to SQL

441

* @param events - Trigger event objects

442

* @returns SQL trigger event

443

*/

444

triggerEventToSQL(events: TriggerEvent[]): string;

445

446

interface TriggerEvent {

447

keyword: string;

448

args?: {

449

keyword: string;

450

columns: any[];

451

};

452

}

453

```

454

455

### Array and Struct Processing

456

457

Functions for handling complex data structures.

458

459

```javascript { .api }

460

/**

461

* Convert array/struct type to SQL

462

* @param expr - Array or struct type definition

463

* @returns SQL array/struct type

464

*/

465

arrayStructTypeToSQL(expr: ArrayStructType): string;

466

467

interface ArrayStructType {

468

dataType: string;

469

definition?: any[];

470

anglebracket?: boolean;

471

}

472

473

/**

474

* Convert column order list to SQL

475

* @param columnOrderList - List of column order specifications

476

* @returns SQL column order clause

477

*/

478

columnOrderListToSQL(columnOrderList: any[]): string;

479

480

/**

481

* Convert common keyword arguments to SQL

482

* @param kwArgs - Keyword arguments object

483

* @returns SQL keyword arguments array

484

*/

485

commonKeywordArgsToSQL(kwArgs: KeywordArgs): string[];

486

487

interface KeywordArgs {

488

keyword: string;

489

args: string;

490

}

491

492

/**

493

* Get common type value

494

* @param opt - Type value options

495

* @returns Array of processed values

496

*/

497

commonTypeValue(opt: TypeValueOptions): string[];

498

499

interface TypeValueOptions {

500

type: string;

501

symbol?: string;

502

value: string | any;

503

}

504

```

505

506

**Usage Examples:**

507

508

```javascript

509

import {

510

arrayStructTypeToSQL,

511

columnOrderListToSQL,

512

commonTypeValue

513

} from 'node-sql-parser/lib/util';

514

515

// Array type processing

516

const arrayType = arrayStructTypeToSQL({

517

dataType: 'ARRAY',

518

definition: [{ field_name: 'id', field_type: { dataType: 'INT' } }],

519

anglebracket: true

520

});

521

console.log(arrayType); // "ARRAY<id INT>"

522

523

// Common type value processing

524

const typeValue = commonTypeValue({

525

type: 'CHARACTER SET',

526

symbol: '=',

527

value: 'utf8'

528

});

529

console.log(typeValue); // ['CHARACTER SET', '=', 'UTF8']

530

```

531

532

These utility functions provide the building blocks for more complex SQL processing and can be used to create custom SQL manipulation tools or extend the parser's functionality for specific use cases.