Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Thêm Primary Key vào câu lệnh CREATE TABLE với JSqlParser

Parser là chương trình hiểu ngữ pháp của chuỗi từ/câu và tạo ra biểu diễn cây cú pháp. Được dùng nhiều lĩnh vực: ngôn ngữ lập trình, xử lý ngôn ngữ tự nhiên, SQL, v.v. Để demo Parser, tham khảo open source JSqlParser.

JSqlParser

JSqlParser là SQL statement parser open source trên Github. Nó parse SQL statement và chuyển thành hierarchy các Java class. Ví dụ sau parse câu lệnh CREATE TABLE dùng JSqlParser. Viết chương trình Java parse CREATE TABLE và thêm primary key.

Câu lệnh CREATE TABLE

CREATE TABLE College_db.Students (
    Student_id int,
    Name varchar(255),
    Course varchar(255),
    Join_date DATE
);

Muốn thêm cột Student_id làm Primary key.

Chương trình Java parse CREATE TABLE SQL dùng JSqlParser

Bước 1: Thêm JSqlParser dependency

Tạo maven project, thêm dependency vào pom.xml:

<dependency>
    <groupId>com.github.jsqlparser</groupId>
    <artifactId>jsqlparser</artifactId>
    <version>4.2</version>
</dependency>

Bước 2: Gán input CREATE TABLE statement vào biến

String createTableSql = "CREATE TABLE College_db.Students (\n" +
    " Student_id int,\n" +
    " Name varchar(255),\n" +
    " Course varchar(255),\n" +
    " Join_date DATE\n" +
    ");";

Bước 3: Parse SQL dùng JSqlParser

Dùng class util CCJSqlParserUtil, gọi method parse với argument CREATE TABLE sql.

Statement createTable = CCJSqlParserUtil.parse(createTableSql);

Sau parse, object Statement createTable có hierarchy Java classes.

Thêm Primary Key vào câu lệnh CREATE TABLE với JSqlParser

Bước 4: Khám phá parser output

Nếu parse thành công, lấy thông tin database/table name và column definition. Cũng đổi database và table name trong CREATE TABLE.

System.out.println("Table Name from query: " + ((CreateTable) createTable).getTable().getName());
System.out.println("Database Name from query: " + ((CreateTable) createTable).getTable().getSchemaName());
System.out.println("\nColumns in the given insert query");
System.out.println("---------------------------------\n");
for(ColumnDefinition col: ((CreateTable) createTable).getColumnDefinitions()) {
    System.out.println(col.getColumnName() + " - " + col.getColDataType().toString());
}
// Đổi DB và table name
((CreateTable) createTable).getTable().setSchemaName("College_db_bk");
((CreateTable) createTable).getTable().setName("Students_bkup");

Bước 5: Tạo primary key constraint làm index

Có thể set các index khác: Check constraint, Exclude constraint, Foreign key, Named constraint. Với primary key, tạo Named constraint:

// Tạo Primary Key constraint
NamedConstraint namedConstraint = new NamedConstraint();
namedConstraint.setType("PRIMARY KEY");

// Thêm column names cho Primary Key
List<Index.ColumnParams> columns = new ArrayList<>();
Index.ColumnParams columnParams = new Index.ColumnParams("Student_id");
columns.add(columnParams);

// Set columns trong Primary Key constraint
namedConstraint.setColumns(columns);

Set Primary key của Student_id làm Named constraint trong index list:

// Set Primary Key constraint trong Index list
List<Index> indexList = new ArrayList<>();
indexList.add(namedConstraint);

Bước 6: Set index trong CREATE TABLE statement

Set index list trong create table để CREATE TABLE statement được generate với Primary key.

((CreateTable) createTable).setIndexes(indexList);

Chương trình Java hoàn chỉnh thêm primary key vào CREATE TABLE SQL

import net.sf.jsqlparser.JSQLParserException;
import net.sf.jsqlparser.parser.CCJSqlParserUtil;
import net.sf.jsqlparser.statement.Statement;
import net.sf.jsqlparser.statement.create.table.ColumnDefinition;
import net.sf.jsqlparser.statement.create.table.CreateTable;
import net.sf.jsqlparser.statement.create.table.Index;
import net.sf.jsqlparser.statement.create.table.NamedConstraint;
import java.util.ArrayList;
import java.util.List;

public class AddPrimaryKey {
    public static void main(String[] args) {
        System.out.println("Adding Primary key in the CREATE TABLE statement");
        System.out.println("-------------------------------------\n");
        String createTableSql = "CREATE TABLE College_db.Students (\n" +
            " Student_id int,\n" +
            " Name varchar(255),\n" +
            " Course varchar(255),\n" +
            " Join_date DATE\n" +
            ");";
        try {
            Statement createTable = CCJSqlParserUtil.parse(createTableSql);
            System.out.println("Table Name from query: " + ((CreateTable) createTable).getTable().getName());
            System.out.println("Database Name from query: " + ((CreateTable) createTable).getTable().getSchemaName());
            System.out.println("\nColumns in the given insert query");
            System.out.println("---------------------------------\n");
            for (ColumnDefinition col : ((CreateTable) createTable).getColumnDefinitions()) {
                System.out.println(col.getColumnName() + " - " + col.getColDataType().toString());
            }
            ((CreateTable) createTable).getTable().setSchemaName("College_db_bk");
            ((CreateTable) createTable).getTable().setName("Students_bkup");
            NamedConstraint namedConstraint = new NamedConstraint();
            namedConstraint.setType("PRIMARY KEY");
            List<Index.ColumnParams> columns = new ArrayList<>();
            Index.ColumnParams columnParams = new Index.ColumnParams("Student_id");
            columns.add(columnParams);
            namedConstraint.setColumns(columns);
            List<Index> indexList = new ArrayList<>();
            indexList.add(namedConstraint);
            ((CreateTable) createTable).setIndexes(indexList);
            System.out.println("New CREATE TABLE statement with Primary Key");
            System.out.println("---------------------------------");
            System.out.println(createTable + ";");
        } catch (JSQLParserException e) {
            throw new RuntimeException(e);
        }
    }
}

Output

CREATE TABLE mới được generate với primary key Student_id. Database và table name đổi thành College_db_bk.Students_bkup.

Adding Primary key in the CREATE TABLE statement
-------------------------------------
Table Name from query: Students
Database Name from query: College_db
Columns in the given insert query
---------------------------------
Student_id - int
Name - varchar (255)
Course - varchar (255)
Join_date - DATE
New CREATE TABLE statement with Primary Key
---------------------------------
CREATE TABLE College_db_bk.Students_bkup (Student_id int, Name varchar (255), Course varchar (255), Join_date DATE, PRIMARY KEY (Student_id));

Bài viết khuyến nghị

  • Apache Hive parser example