All Downloads are FREE. Search and download functionalities are using the official Maven repository.

xtdb.antlr.clj Maven / Gradle / Ivy

The newest version!
(ns xtdb.antlr
  (:require [xtdb.error :as err])
  (:import (com.github.benmanes.caffeine.cache Cache Caffeine)
           (org.antlr.v4.runtime BaseErrorListener CharStreams CommonTokenStream Recognizer)
           (xtdb.antlr Sql SqlLexer)))

(def ^:private ^com.github.benmanes.caffeine.cache.Cache parser-cache
  (-> (Caffeine/newBuilder)
      (.maximumSize 4096)
      (.build)))

(defn add-throwing-error-listener [^Recognizer x]
  (doto x
    (.removeErrorListeners)
    (.addErrorListener
     (proxy
      [BaseErrorListener] []
       (syntaxError [_ _ line char-position-in-line msg _]
         (throw
          (err/illegal-arg :xtdb/sql-error
                           {::err/message (str "Errors parsing SQL statement:\n  - "
                                               (format "line %s:%s %s" line char-position-in-line msg))})))))))

(defn ->parser ^xtdb.antlr.Sql [sql]
  (-> (SqlLexer. (CharStreams/fromString sql))
      (add-throwing-error-listener)
      (CommonTokenStream.)
      (Sql.)
      (add-throwing-error-listener)))

(defn parse-statement ^xtdb.antlr.Sql$DirectlyExecutableStatementContext [sql]
  (.get parser-cache sql
        (fn [sql]
          (let [parser (->parser sql)]
            (-> (.directSqlStatement parser)
                (.directlyExecutableStatement)
                #_(doto (-> (.toStringTree parser) read-string (clojure.pprint/pprint)))))))) ; <>




© 2015 - 2024 Weber Informatics LLC | Privacy Policy