package com.taosdata.jdbc.cases;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.sql.*;
import java.util.concurrent.TimeUnit;

public class MultiThreadsWithSameStatementTest {


    private class Service {
        public Connection conn;
        public Statement stmt;

        public Service() {
            try {
                conn = DriverManager.getConnection("jdbc:TAOS://localhost:6030/?user=root&password=taosdata");
                stmt = conn.createStatement();
                stmt.execute("create database if not exists jdbctest");
                stmt.executeUpdate("create table if not exists jdbctest.weather (ts timestamp, f1 int)");
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        public void release() {
            try {
                stmt.close();
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    @Before
    public void before() {
    }

    @Test
    public void test() {
        Thread t1 = new Thread(() -> {
            try {
                Service service = new Service();
                ResultSet resultSet = service.stmt.executeQuery("select * from jdbctest.weather");
                while (resultSet.next()) {
                    ResultSetMetaData metaData = resultSet.getMetaData();
                }
                resultSet.close();
                service.release();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        });

        Thread t2 = new Thread(() -> {
            while (true) {
                try {
                    Service service = new Service();
                    service.stmt.executeUpdate("insert into jdbctest.weather values(now,1)");
                    service.release();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

        });
        t1.start();
        sleep(1000);
        t2.start();
    }

    private void sleep(long mills) {
        try {
            TimeUnit.MILLISECONDS.sleep(mills);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @After
    public void after() {
    }
}
