Skip to content

Getting Started with GSP

Welcome to your first tutorial on General SQL Parser! This comprehensive guide will take you from zero to parsing your first SQL statements in about 30 minutes.

๐ŸŽฏ Objectives

By the end of this tutorial, you will:

  • Understand what General SQL Parser is and how it works
  • Set up GSP in your Java project
  • Parse your first SQL statement
  • Understand the parsing results and AST structure
  • Handle basic parsing errors
  • Know the core concepts and terminology

๐Ÿ“‹ Prerequisites

  • Java 8+ installed and configured
  • Maven or Gradle for dependency management
  • IDE (IntelliJ IDEA, Eclipse, or VS Code)
  • Basic understanding of SQL syntax
  • Familiarity with Java programming

โฑ๏ธ Time Required

Approximately 30 minutes

๐Ÿ”ง Setup

Step 1: Create a New Java Project

Create a new Maven or Gradle project in your IDE:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
         http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>gsp-tutorial</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>com.gudusoft</groupId>
            <artifactId>gsqlparser</artifactId>
            <version>3.3.2</version>
        </dependency>
    </dependencies>
</project>
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
plugins {
    id 'java'
}

group 'com.example'
version '1.0-SNAPSHOT'

repositories {
    mavenCentral()
}

dependencies {
    implementation 'com.gudusoft:gsqlparser:3.3.2'
}

java {
    sourceCompatibility = JavaVersion.VERSION_1_8
    targetCompatibility = JavaVersion.VERSION_1_8
}

Step 2: Verify Installation

Create a simple test class to verify GSP is working:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
package com.example.gsptutorial;

import gudusoft.gsqlparser.TGSqlParser;
import gudusoft.gsqlparser.EDbVendor;

public class GSPTest {
    public static void main(String[] args) {
        System.out.println("Testing General SQL Parser...");

        TGSqlParser parser = new TGSqlParser(EDbVendor.dbvoracle);
        System.out.println("Parser created successfully!");
        System.out.println("Database vendor: " + parser.getDbVendor());
    }
}

Run this class. You should see:

1
2
3
Testing General SQL Parser...
Parser created successfully!
Database vendor: dbvoracle

๐Ÿ“ Step-by-Step Guide

Step 3: Understanding Core Concepts

Before we start parsing, let's understand the key concepts:

!!! info "Core Concepts"

1
2
3
4
5
6
7
8
9
**TGSqlParser** - The main parser class that processes SQL text

**EDbVendor** - Enum specifying the database vendor (Oracle, SQL Server, etc.)

**AST (Abstract Syntax Tree)** - The structured representation of parsed SQL

**SQL Statements** - Individual SQL commands (SELECT, INSERT, etc.)

**Parse Result** - Integer return code (0 = success, non-zero = error)

Step 4: Your First Parse

Let's parse a simple SELECT statement:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package com.example.gsptutorial;

import gudusoft.gsqlparser.TGSqlParser;
import gudusoft.gsqlparser.EDbVendor;

public class FirstParse {
    public static void main(String[] args) {
        // Step 1: Create parser for Oracle SQL
        TGSqlParser parser = new TGSqlParser(EDbVendor.dbvoracle);

        // Step 2: Set the SQL text to parse
        String sql = "SELECT employee_id, first_name, last_name FROM employees";
        parser.sqltext = sql;

        // Step 3: Parse the SQL
        int result = parser.parse();

        // Step 4: Check the result
        if (result == 0) {
            System.out.println("โœ… Parse successful!");
            System.out.println("Number of statements: " + parser.sqlstatements.size());
            System.out.println("Statement type: " + parser.sqlstatements.get(0).sqlstatementtype);
        } else {
            System.out.println("โŒ Parse failed!");
            System.out.println("Error: " + parser.getErrormessage());
        }
    }
}

Expected Output:

1
2
3
โœ… Parse successful!
Number of statements: 1
Statement type: sstselect

Step 5: Exploring the AST

Now let's explore what we can extract from the parsed SQL:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package com.example.gsptutorial;

import gudusoft.gsqlparser.TGSqlParser;
import gudusoft.gsqlparser.EDbVendor;
import gudusoft.gsqlparser.stmt.TSelectSqlStatement;
import gudusoft.gsqlparser.TTable;

public class ExploreAST {
    public static void main(String[] args) {
        TGSqlParser parser = new TGSqlParser(EDbVendor.dbvoracle);
        parser.sqltext = "SELECT emp.employee_id, emp.first_name, dept.department_name " +
                        "FROM employees emp " +
                        "JOIN departments dept ON emp.department_id = dept.department_id " +
                        "WHERE emp.salary > 50000";

        if (parser.parse() == 0) {
            // Cast to SELECT statement
            TSelectSqlStatement select = (TSelectSqlStatement) parser.sqlstatements.get(0);

            // Extract tables
            System.out.println("๐Ÿ“‹ Tables used:");
            for (int i = 0; i < select.tables.size(); i++) {
                TTable table = select.tables.getTable(i);
                System.out.println("  - " + table.getTableName() + 
                    (table.getAliasClause() != null ? " (alias: " + table.getAliasClause() + ")" : ""));
            }

            // Extract columns
            System.out.println("\n๐Ÿ“Š Columns selected:");
            for (int i = 0; i < select.getResultColumnList().size(); i++) {
                System.out.println("  - " + select.getResultColumnList().getResultColumn(i).toString());
            }

            // Check for WHERE clause
            if (select.getWhereClause() != null) {
                System.out.println("\n๐Ÿ” WHERE condition:");
                System.out.println("  " + select.getWhereClause().toString());
            }
        }
    }
}

Expected Output:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
๐Ÿ“‹ Tables used:
  - employees (alias: emp)
  - departments (alias: dept)

๐Ÿ“Š Columns selected:
  - emp.employee_id
  - emp.first_name
  - dept.department_name

๐Ÿ” WHERE condition:
  emp.salary > 50000

Step 6: Handling Different Database Vendors

GSP supports 30+ database vendors. Let's see how to handle different SQL dialects:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package com.example.gsptutorial;

import gudusoft.gsqlparser.TGSqlParser;
import gudusoft.gsqlparser.EDbVendor;

public class MultiVendorExample {
    public static void main(String[] args) {
        // Test different database-specific SQL
        testOracleSQL();
        testSQLServerSQL();
        testPostgreSQLSQL();
        testMySQLSQL();
    }

    private static void testOracleSQL() {
        System.out.println("๐Ÿ”ถ Testing Oracle SQL:");
        TGSqlParser parser = new TGSqlParser(EDbVendor.dbvoracle);
        parser.sqltext = "SELECT * FROM dual WHERE ROWNUM = 1";

        if (parser.parse() == 0) {
            System.out.println("  โœ… Oracle SQL parsed successfully");
        } else {
            System.out.println("  โŒ Error: " + parser.getErrormessage());
        }
    }

    private static void testSQLServerSQL() {
        System.out.println("\n๐Ÿ”ท Testing SQL Server SQL:");
        TGSqlParser parser = new TGSqlParser(EDbVendor.dbvmssql);
        parser.sqltext = "SELECT TOP 10 * FROM employees";

        if (parser.parse() == 0) {
            System.out.println("  โœ… SQL Server SQL parsed successfully");
        } else {
            System.out.println("  โŒ Error: " + parser.getErrormessage());
        }
    }

    private static void testPostgreSQLSQL() {
        System.out.println("\n๐Ÿ˜ Testing PostgreSQL SQL:");
        TGSqlParser parser = new TGSqlParser(EDbVendor.dbvpostgresql);
        parser.sqltext = "SELECT * FROM employees LIMIT 10 OFFSET 5";

        if (parser.parse() == 0) {
            System.out.println("  โœ… PostgreSQL SQL parsed successfully");
        } else {
            System.out.println("  โŒ Error: " + parser.getErrormessage());
        }
    }

    private static void testMySQLSQL() {
        System.out.println("\n๐Ÿฌ Testing MySQL SQL:");
        TGSqlParser parser = new TGSqlParser(EDbVendor.dbvmysql);
        parser.sqltext = "SELECT * FROM employees LIMIT 5, 10";

        if (parser.parse() == 0) {
            System.out.println("  โœ… MySQL SQL parsed successfully");
        } else {
            System.out.println("  โŒ Error: " + parser.getErrormessage());
        }
    }
}

Step 7: Error Handling

Let's learn how to handle parsing errors properly:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package com.example.gsptutorial;

import gudusoft.gsqlparser.TGSqlParser;
import gudusoft.gsqlparser.EDbVendor;

public class ErrorHandlingExample {
    public static void main(String[] args) {
        // Test with invalid SQL
        testInvalidSQL();

        // Test with wrong vendor
        testWrongVendor();
    }

    private static void testInvalidSQL() {
        System.out.println("๐Ÿšซ Testing invalid SQL:");
        TGSqlParser parser = new TGSqlParser(EDbVendor.dbvoracle);
        parser.sqltext = "SELECT * FROM"; // Missing table name

        int result = parser.parse();
        if (result != 0) {
            System.out.println("  โŒ Parse failed as expected");
            System.out.println("  ๐Ÿ“ Error message: " + parser.getErrormessage());
            System.out.println("  ๐Ÿ“ Error position: " + parser.getErrorLocation());
            System.out.println("  ๐Ÿ“ Line: " + parser.getErrorLine());
            System.out.println("  ๐Ÿ“ Column: " + parser.getErrorColumn());
        }
    }

    private static void testWrongVendor() {
        System.out.println("\n๐Ÿ”„ Testing SQL Server syntax with Oracle parser:");
        TGSqlParser parser = new TGSqlParser(EDbVendor.dbvoracle);
        parser.sqltext = "SELECT TOP 10 * FROM employees"; // SQL Server syntax

        int result = parser.parse();
        if (result != 0) {
            System.out.println("  โŒ Parse failed - wrong vendor");
            System.out.println("  ๐Ÿ’ก Tip: Use EDbVendor.dbvmssql for SQL Server syntax");
        }
    }
}

๐Ÿงช Practice Exercises

Try these exercises to reinforce your learning:

!!! note "Exercise 1: Parse Different Statement Types"

1
2
3
4
5
6
7
8
Parse these SQL statements and identify their types:

```sql
INSERT INTO employees (id, name) VALUES (1, 'John');
UPDATE employees SET salary = 60000 WHERE id = 1;
DELETE FROM employees WHERE id = 1;
CREATE TABLE test (id INT, name VARCHAR(50));
```

!!! note "Exercise 2: Extract Information"

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
For this complex query, extract all table names, column names, and join conditions:

```sql
SELECT e.employee_id, e.first_name, d.department_name, l.city
FROM employees e
JOIN departments d ON e.department_id = d.department_id
JOIN locations l ON d.location_id = l.location_id
WHERE e.hire_date > '2020-01-01'
ORDER BY e.last_name;
```

!!! note "Exercise 3: Error Recovery"

1
2
3
4
5
6
7
Create a method that tries to parse SQL with different vendors until it succeeds:

```java
public static EDbVendor detectVendor(String sql) {
    // Try different vendors and return the one that works
}
```

โœ… Summary

Congratulations! You've completed your first GSP tutorial. Here's what you learned:

  • โœ… How to set up General SQL Parser in your project
  • โœ… Core concepts: TGSqlParser, EDbVendor, AST
  • โœ… How to parse SQL statements and check results
  • โœ… How to extract information from the AST
  • โœ… How to handle different database vendors
  • โœ… How to handle parsing errors gracefully

Key Takeaways

  1. Always check the parse result - 0 means success, non-zero means error
  2. Choose the right vendor - SQL syntax varies between databases
  3. Handle errors gracefully - Provide meaningful error messages
  4. Explore the AST - Rich information is available in the parsed structure

What's Next?

Now that you understand the basics, continue with:


Ready for the next challenge? Continue with Basic SQL Parsing ๐Ÿš€