├── .gitignore ├── LICENSE.txt ├── README.md ├── deps.edn ├── resources └── metabase-plugin.yaml ├── src └── metabase │ └── driver │ ├── sql │ └── util │ │ └── deduplicate.clj │ └── teradata.clj └── test └── metabase ├── driver └── teradata_test.clj └── test └── data └── teradata.clj /.gitignore: -------------------------------------------------------------------------------- 1 | \#*\# 2 | .\#* 3 | /target 4 | /.nrepl-port 5 | /bin 6 | .classpath 7 | .project 8 | .idea 9 | *.iml 10 | teradata-driver.iml 11 | .lein-repl-history 12 | .cpcache -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | Eclipse Public License - v 1.0 2 | 3 | THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. 4 | 5 | 1. DEFINITIONS 6 | 7 | "Contribution" means: 8 | 9 | a) in the case of the initial Contributor, the initial code and documentation distributed under this Agreement, and 10 | b) in the case of each subsequent Contributor: 11 | i) changes to the Program, and 12 | ii) additions to the Program; 13 | 14 | where such changes and/or additions to the Program originate from and are distributed by that particular Contributor. A Contribution 'originates' from a Contributor if it was added to the Program by such Contributor itself or anyone acting on such Contributor's behalf. Contributions do not include additions to the Program which: (i) are separate modules of software distributed in conjunction with the Program under their own license agreement, and (ii) are not derivative works of the Program. 15 | "Contributor" means any person or entity that distributes the Program. 16 | 17 | "Licensed Patents" mean patent claims licensable by a Contributor which are necessarily infringed by the use or sale of its Contribution alone or when combined with the Program. 18 | 19 | "Program" means the Contributions distributed in accordance with this Agreement. 20 | 21 | "Recipient" means anyone who receives the Program under this Agreement, including all Contributors. 22 | 23 | 2. GRANT OF RIGHTS 24 | 25 | a) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free copyright license to reproduce, prepare derivative works of, publicly display, publicly perform, distribute and sublicense the Contribution of such Contributor, if any, and such derivative works, in source code and object code form. 26 | b) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free patent license under Licensed Patents to make, use, sell, offer to sell, import and otherwise transfer the Contribution of such Contributor, if any, in source code and object code form. This patent license shall apply to the combination of the Contribution and the Program if, at the time the Contribution is added by the Contributor, such addition of the Contribution causes such combination to be covered by the Licensed Patents. The patent license shall not apply to any other combinations which include the Contribution. No hardware per se is licensed hereunder. 27 | c) Recipient understands that although each Contributor grants the licenses to its Contributions set forth herein, no assurances are provided by any Contributor that the Program does not infringe the patent or other intellectual property rights of any other entity. Each Contributor disclaims any liability to Recipient for claims brought by any other entity based on infringement of intellectual property rights or otherwise. As a condition to exercising the rights and licenses granted hereunder, each Recipient hereby assumes sole responsibility to secure any other intellectual property rights needed, if any. For example, if a third party patent license is required to allow Recipient to distribute the Program, it is Recipient's responsibility to acquire that license before distributing the Program. 28 | d) Each Contributor represents that to its knowledge it has sufficient copyright rights in its Contribution, if any, to grant the copyright license set forth in this Agreement. 29 | 30 | 3. REQUIREMENTS 31 | 32 | A Contributor may choose to distribute the Program in object code form under its own license agreement, provided that: 33 | 34 | a) it complies with the terms and conditions of this Agreement; and 35 | b) its license agreement: 36 | i) effectively disclaims on behalf of all Contributors all warranties and conditions, express and implied, including warranties or conditions of title and non-infringement, and implied warranties or conditions of merchantability and fitness for a particular purpose; 37 | ii) effectively excludes on behalf of all Contributors all liability for damages, including direct, indirect, special, incidental and consequential damages, such as lost profits; 38 | iii) states that any provisions which differ from this Agreement are offered by that Contributor alone and not by any other party; and 39 | iv) states that source code for the Program is available from such Contributor, and informs licensees how to obtain it in a reasonable manner on or through a medium customarily used for software exchange. 40 | 41 | When the Program is made available in source code form: 42 | 43 | a) it must be made available under this Agreement; and 44 | b) a copy of this Agreement must be included with each copy of the Program. 45 | 46 | Contributors may not remove or alter any copyright notices contained within the Program. 47 | 48 | Each Contributor must identify itself as the originator of its Contribution, if any, in a manner that reasonably allows subsequent Recipients to identify the originator of the Contribution. 49 | 50 | 4. COMMERCIAL DISTRIBUTION 51 | 52 | Commercial distributors of software may accept certain responsibilities with respect to end users, business partners and the like. While this license is intended to facilitate the commercial use of the Program, the Contributor who includes the Program in a commercial product offering should do so in a manner which does not create potential liability for other Contributors. Therefore, if a Contributor includes the Program in a commercial product offering, such Contributor ("Commercial Contributor") hereby agrees to defend and indemnify every other Contributor ("Indemnified Contributor") against any losses, damages and costs (collectively "Losses") arising from claims, lawsuits and other legal actions brought by a third party against the Indemnified Contributor to the extent caused by the acts or omissions of such Commercial Contributor in connection with its distribution of the Program in a commercial product offering. The obligations in this section do not apply to any claims or Losses relating to any actual or alleged intellectual property infringement. In order to qualify, an Indemnified Contributor must: a) promptly notify the Commercial Contributor in writing of such claim, and b) allow the Commercial Contributor to control, and cooperate with the Commercial Contributor in, the defense and any related settlement negotiations. The Indemnified Contributor may participate in any such claim at its own expense. 53 | 54 | For example, a Contributor might include the Program in a commercial product offering, Product X. That Contributor is then a Commercial Contributor. If that Commercial Contributor then makes performance claims, or offers warranties related to Product X, those performance claims and warranties are such Commercial Contributor's responsibility alone. Under this section, the Commercial Contributor would have to defend claims against the other Contributors related to those performance claims and warranties, and if a court requires any other Contributor to pay any damages as a result, the Commercial Contributor must pay those damages. 55 | 56 | 5. NO WARRANTY 57 | 58 | EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is solely responsible for determining the appropriateness of using and distributing the Program and assumes all risks associated with its exercise of rights under this Agreement , including but not limited to the risks and costs of program errors, compliance with applicable laws, damage to or loss of data, programs or equipment, and unavailability or interruption of operations. 59 | 60 | 6. DISCLAIMER OF LIABILITY 61 | 62 | EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 63 | 64 | 7. GENERAL 65 | 66 | If any provision of this Agreement is invalid or unenforceable under applicable law, it shall not affect the validity or enforceability of the remainder of the terms of this Agreement, and without further action by the parties hereto, such provision shall be reformed to the minimum extent necessary to make such provision valid and enforceable. 67 | 68 | If Recipient institutes patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Program itself (excluding combinations of the Program with other software or hardware) infringes such Recipient's patent(s), then such Recipient's rights granted under Section 2(b) shall terminate as of the date such litigation is filed. 69 | 70 | All Recipient's rights under this Agreement shall terminate if it fails to comply with any of the material terms or conditions of this Agreement and does not cure such failure in a reasonable period of time after becoming aware of such noncompliance. If all Recipient's rights under this Agreement terminate, Recipient agrees to cease use and distribution of the Program as soon as reasonably practicable. However, Recipient's obligations under this Agreement and any licenses granted by Recipient relating to the Program shall continue and survive. 71 | 72 | Everyone is permitted to copy and distribute copies of this Agreement, but in order to avoid inconsistency the Agreement is copyrighted and may only be modified in the following manner. The Agreement Steward reserves the right to publish new versions (including revisions) of this Agreement from time to time. No one other than the Agreement Steward has the right to modify this Agreement. The Eclipse Foundation is the initial Agreement Steward. The Eclipse Foundation may assign the responsibility to serve as the Agreement Steward to a suitable separate entity. Each new version of the Agreement will be given a distinguishing version number. The Program (including Contributions) may always be distributed subject to the version of the Agreement under which it was received. In addition, after a new version of the Agreement is published, Contributor may elect to distribute the Program (including its Contributions) under the new version. Except as expressly stated in Sections 2(a) and 2(b) above, Recipient receives no rights or licenses to the intellectual property of any Contributor under this Agreement, whether expressly, by implication, estoppel or otherwise. All rights in the Program not expressly granted under this Agreement are reserved. 73 | 74 | This Agreement is governed by the laws of the State of New York and the intellectual property laws of the United States of America. No party to this Agreement will bring a legal action under this Agreement more than one year after the cause of action arose. Each party waives its rights to a jury trial in any resulting litigation. 75 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Metabase Teradata Driver (Community-Supported) 2 | 3 | The Metabase Teradata driver allows Metabase SNAPSHOT to connect to [Teradata](https://www.teradata.com/) databases. 4 | Instructions for installing it can be found below. 5 | As soon as the required commit is merged into a future Metabase release version, this driver can be aligned with Metabase tags. 6 | 7 | This driver is community-supported and is not considered part of the 8 | core Metabase project. If you would like to open a GitHub issue to 9 | report a bug or request new features, or would like to open a pull 10 | requests against it, please do so in this repository, and not in the 11 | core Metabase GitHub repository. 12 | 13 | ## Obtaining the Teradata Driver 14 | 15 | ### Where to find it 16 | 17 | [Click here](https://github.com/swisscom-bigdata/metabase-teradata-driver/releases/latest) to view the latest release of the Metabase Teradata driver; click the link to download `teradata.metabase-driver.jar`. 18 | 19 | You can find past releases of the Teradata driver [here](https://github.com/swisscom-bigdata/metabase-teradata-driver/releases). 20 | 21 | 22 | ### How to Install it 23 | 24 | Metabase will automatically make the Teradata driver available if it finds the driver and the proprietary jdbc JARs in the Metabase plugins directory when it starts up. 25 | All you need to do is create the directory `plugins` (if it's not already there), move the JAR you just downloaded into it, and restart Metabase. 26 | 27 | By default, the plugins directory is called `plugins`, and lives in the same directory as the Metabase JAR. 28 | 29 | For example, if you're running Metabase from a directory called `/app/`, you should move the Teradata driver and the proprietary jdbc JARs to `/app/plugins/`: 30 | 31 | ```bash 32 | # example directory structure for running Metabase with Teradata support 33 | /app/metabase.jar 34 | /app/plugins/teradata.metabase-driver.jar 35 | /app/plugins/terajdbc4.jar 36 | ``` 37 | 38 | If you're running Metabase from the Mac App, the plugins directory defaults to `~/Library/Application Support/Metabase/Plugins/`: 39 | 40 | ```bash 41 | # example directory structure for running Metabase Mac App with Teradata support 42 | /Users/you/Library/Application Support/Metabase/Plugins/teradata.metabase-driver.jar 43 | /Users/you/Library/Application Support/Metabase/Plugins/terajdbc4.jar 44 | ``` 45 | 46 | If you are running the Docker image or you want to use another directory for plugins, you should specify a custom plugins directory by setting the environment variable `MB_PLUGINS_DIR`. 47 | 48 | 49 | ## Building the Teradata Driver Yourself 50 | 51 | ## One time setup of metabase 52 | 53 | You require metabase to be installed alongside of your project 54 | 1. cd metadata-teradata-driver/.. 55 | 2. execute 56 | ``` 57 | git clone https://github.com/metabase/metabase 58 | cd metabase 59 | clojure -X:deps prep 60 | cd modules/drivers 61 | clojure -X:deps prep 62 | cd ../../../metabase-teradata-driver 63 | ``` 64 | 65 | ## Build 66 | 1. under the metabase folder, check out the desired branch 67 | 2. create a link to the right location to the driver: 68 | ``` 69 | DRIVER_PATH=`readlink -f /home/user/metadata-teradata-driver/` 70 | ``` 71 | 3. 72 | ``` 73 | clojure -Sdeps "{:aliases {:teradata {:extra-deps {com.metabase/teradata-driver {:local/root \"$DRIVER_PATH\"}}}}}" -X:build:teradata build-drivers.build-driver/build-driver! "{:driver :teradata :project-dir \"$DRIVER_PATH\", :target-dir \"$DRIVER_PATH/target\"}" 74 | ``` 75 | 76 | This will build a file called `target/teradata.metabase-driver.jar` under the driver folder; copy this to your Metabase `./plugins` directory. 77 | 78 | 79 | ## Tests 80 | 81 | Invoking the test-runner with `clojure -X` will call the test function with a map of arguments, 82 | which can be supplied either in the alias (via `:exec-args`) or on the command-line, or both. 83 | 84 | Invoke it with: 85 | 86 | ```bash 87 | clj -X:test ...args... 88 | ``` 89 | 90 | This will scan your project's `test` directory for any tests defined 91 | using `clojure.test` and run them. 92 | 93 | You may also supply any of the additional command line options: 94 | 95 | ``` 96 | :dirs - coll of directories containing tests, default= ["test"] 97 | :nses - coll of namespace symbols to test 98 | :patterns - coll of regex strings to match namespaces 99 | :vars - coll of fully qualified symbols to run tests on 100 | :includes - coll of test metadata keywords to include 101 | :excludes - coll of test metadata keywords to exclude" 102 | ``` 103 | 104 | If neither :dirs or :nses is supplied, will use: 105 | 106 | ``` 107 | :patterns [".*-test$"] 108 | ``` -------------------------------------------------------------------------------- /deps.edn: -------------------------------------------------------------------------------- 1 | { 2 | :paths [ 3 | ; in case you get the error `All dirs should be absolute`, you forgot to define an absolute project-dir like so: 4 | ; clojure -X:build :project-dir "\"$(pwd)\"" 5 | "src" 6 | "resources" 7 | ] 8 | 9 | :deps { org.clojure/core.logic {:mvn/version "1.0.1"} 10 | com.github.seancorfield/honeysql {:mvn/version "2.5.1103"} 11 | } 12 | 13 | ;; These are needed for the Athena and Redshift drivers in order to build them. Maven repos from subprojects do not 14 | ;; get copied over -- see 15 | ;; https://ask.clojure.org/index.php/10726/deps-manifest-dependencies-respect-repos-dependent-project 16 | :mvn/repos 17 | {"athena" {:url "https://s3.amazonaws.com/maven-athena"} 18 | "redshift" {:url "https://s3.amazonaws.com/redshift-maven-repository/release"}} 19 | 20 | ; build the driver with `clojure -X:build :project-dir "\"$(pwd)\""` 21 | :aliases 22 | {:dev 23 | {:extra-deps 24 | { io.github.metabase/metabase { :git/tag "v0.50.31", :git/sha "33dddaa" } } 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /resources/metabase-plugin.yaml: -------------------------------------------------------------------------------- 1 | info: 2 | name: Metabase Teradata Driver 3 | # also replace the version in deps.edn if you change the metabase version here 4 | version: 1.1.17-metabase-v0.50.31-teradata-jdbc-20.00 5 | description: Allows Metabase to connect to Teradata databases. Community Supported driver. 6 | dependencies: 7 | - class: com.teradata.jdbc.TeraDriver 8 | message: > 9 | Metabase requires the Teradata terajdbc4.jar in order to be able to connect to Teradata databases. 10 | driver: 11 | name: teradata 12 | display-name: Teradata 13 | lazy-load: true 14 | parent: sql-jdbc 15 | connection-properties: 16 | - host 17 | - merge: 18 | - port 19 | - default: 1025 20 | - name: dbnames 21 | display-name: Database name(s) (case sensitive) 22 | placeholder: Comma-separated list of database names 23 | - user 24 | - password 25 | - ssl 26 | - name: encrypt-data 27 | display-name: Encrypt data 28 | default: true 29 | type: boolean 30 | - advanced-options-start 31 | - name: tmode 32 | display-name: Transaction mode 33 | default: ANSI 34 | visible-if: 35 | advanced-options: true 36 | - merge: 37 | - additional-options 38 | - placeholder: e.g. COPLAST=OFF 39 | # required in order that `Choose when syncs and scans happen` shows up in database options afterwards 40 | # (during first time setup, you only see `Periodically refingerprint tables` in metabase v0.54.4 41 | # the option `Choose when syncs and scans happen` only shows up later in admin -> Database -> advanced options) 42 | - default-advanced-options 43 | connection-properties-include-tunnel-config: false 44 | init: 45 | - step: load-namespace 46 | namespace: metabase.driver.teradata 47 | - step: register-jdbc-driver 48 | class: com.teradata.jdbc.TeraDriver 49 | -------------------------------------------------------------------------------- /src/metabase/driver/sql/util/deduplicate.clj: -------------------------------------------------------------------------------- 1 | (ns metabase.driver.sql.util.deduplicate 2 | "Utility function for de-duplication as used by Oracle and Teradata drivers. Extracted from Oracle driver" 3 | (:require [clojure.string :as str])) 4 | 5 | (defn- increment-identifier-suffix 6 | "Add an appropriate suffix to a keyword IDENTIFIER to make it distinct from previous usages of the same identifier, 7 | e.g. 8 | 9 | (increment-identifier-suffix :my_col) ; -> :my_col_2 10 | (increment-identifier-suffix :my_col_2) ; -> :my_col_3" 11 | [identifier] 12 | (keyword 13 | (let [identifier (name identifier)] 14 | (if-let [[_ existing-suffix] (re-find #"^.*_(\d+$)" identifier)] 15 | ;; if identifier already has an alias like col_2 then increment it to col_3 16 | (let [new-suffix (str (inc (Integer/parseInt existing-suffix)))] 17 | (clojure.string/replace identifier (re-pattern (str existing-suffix \$)) new-suffix)) 18 | ;; otherwise just stick a _2 on the end so it's col_2 19 | (str identifier "_2"))))) 20 | 21 | (defn- alias-everything 22 | "Make sure all the columns in SELECT-CLAUSE are alias forms, e.g. `[:table.col :col]` instead of `:table.col`. 23 | (This faciliates our deduplication logic.)" 24 | [select-clause] 25 | (for [col select-clause] 26 | (if (sequential? col) 27 | ;; if something's already an alias form like [:table.col :col] it's g2g 28 | col 29 | ;; otherwise if it's something like :table.col replace with [:table.col :col] 30 | [col (keyword (last (clojure.string/split (name col) #"\.")))]))) 31 | 32 | (defn deduplicate-identifiers 33 | "Make sure every column in SELECT-CLAUSE has a unique alias. 34 | This is done because Oracle can't figure out how to use a query 35 | that produces duplicate columns in a subselect." 36 | [select-clause] 37 | (if (= select-clause [:*]) 38 | ;; if we're doing `SELECT *` there's no way we can deduplicate anything so we're SOL, return as-is 39 | select-clause 40 | ;; otherwise we can actually deduplicate things 41 | (loop [already-seen #{}, acc [], [[col alias] & more] (alias-everything select-clause)] 42 | (cond 43 | ;; if not more cols are left to deduplicate, we're done 44 | (not col) acc 45 | ;; otherwise if we've already used this alias, replace it with one like `identifier_2` and try agan 46 | (contains? already-seen alias) (recur already-seen acc (cons [col (increment-identifier-suffix alias)] 47 | more)) 48 | ;; otherwise if we haven't seen it record it as seen and move on to the next column 49 | :else (recur (conj already-seen alias) (conj acc [col alias]) more))))) -------------------------------------------------------------------------------- /src/metabase/driver/teradata.clj: -------------------------------------------------------------------------------- 1 | (ns metabase.driver.teradata 2 | (:require [clojure 3 | [set :as set] 4 | [string :as s]] 5 | [medley.core :as m] 6 | [clojure.tools.logging :as log] 7 | [clojure.java.jdbc :as jdbc] 8 | [java-time :as t] 9 | [metabase 10 | [driver :as driver] 11 | [util :as u] 12 | [config :as config]] 13 | [metabase.driver.sql-jdbc.common :as sql-jdbc.common] 14 | [metabase.driver.sql-jdbc.connection :as sql-jdbc.conn] 15 | [metabase.driver.sql-jdbc.execute :as sql-jdbc.execute] 16 | [metabase.driver.sql-jdbc.sync :as sql-jdbc.sync] 17 | [metabase.driver.sql.query-processor :as sql.qp] 18 | [metabase.driver.sql.util.deduplicate :as deduplicateutil] 19 | [metabase.driver.sql-jdbc.sync.common :as sql-jdbc.sync.common] 20 | [metabase.driver.sql-jdbc.sync.describe-table :as sql-jdbc.describe-table] 21 | [metabase.driver.sql-jdbc.sync.interface :as sql-jdbc.sync.interface] 22 | [metabase.util.i18n :refer [trs]] 23 | [metabase.util.honey-sql-2 :as h2x]) 24 | (:import [java.sql Connection DatabaseMetaData ResultSet Types PreparedStatement] 25 | [java.time OffsetDateTime OffsetTime] 26 | [java.util Calendar TimeZone])) 27 | 28 | (driver/register! :teradata, :parent :sql-jdbc) 29 | 30 | (doseq [[feature supported?] {:metadata/key-constraints false}] 31 | (defmethod driver/database-supports? [:teradata feature] [_driver _feature _db] supported?)) 32 | 33 | (defmethod sql-jdbc.sync/database-type->base-type :teradata [_ column-type] 34 | (let [type-mapping 35 | {:BIGINT :type/BigInteger 36 | :BIGSERIAL :type/BigInteger 37 | :BIT :type/* 38 | :BLOB :type/* 39 | :BOX :type/* 40 | :CHAR :type/Text 41 | :CLOB :type/Text 42 | :BYTE :type/* 43 | :BYTEINT :type/Integer 44 | :DATE :type/Date 45 | :DECIMAL :type/Decimal 46 | :FLOAT :type/Float 47 | :FLOAT4 :type/Float 48 | :FLOAT8 :type/Float 49 | :INTEGER :type/Integer 50 | :INT :type/Integer 51 | :INT2 :type/Integer 52 | :INT4 :type/Integer 53 | :INT8 :type/BigInteger 54 | :INTERVAL :type/* ; time span 55 | :JSON :type/Text 56 | :LONGVARCHAR :type/Text ; Teradata extension 57 | :LSEG :type/* 58 | :MACADDR :type/Text 59 | :MONEY :type/Decimal 60 | :NUMERIC :type/Decimal 61 | :NUMBER :type/Decimal ; Add this mapping 62 | :PATH :type/* 63 | :POINT :type/* 64 | :REAL :type/Float 65 | :SERIAL :type/Integer 66 | :SERIAL2 :type/Integer 67 | :SERIAL4 :type/Integer 68 | :SERIAL8 :type/BigInteger 69 | :SMALLINT :type/Integer 70 | :SMALLSERIAL :type/Integer 71 | :TIME :type/Time 72 | (keyword "TIME WITH TIME ZONE") :type/Time 73 | :TIMESTAMP :type/DateTime 74 | (keyword "TIMESTAMP WITH TIME ZONE") :type/DateTime 75 | :TSQUERY :type/* 76 | :TSVECTOR :type/* 77 | :TXID_SNAPSHOT :type/* 78 | :UUID :type/UUID 79 | :VARBIT :type/* 80 | :VARBYTE :type/* ; byte array 81 | :VARCHAR :type/Text 82 | :XML :type/Text 83 | (keyword "bit varying") :type/* 84 | (keyword "character varying") :type/Text 85 | (keyword "double precision") :type/Float 86 | (keyword "time with time zone") :type/Time 87 | (keyword "time without time zone") :type/Time 88 | (keyword "timestamp with timezone") :type/DateTime 89 | (keyword "timestamp without timezone") :type/DateTime}] 90 | (get type-mapping column-type :type/*))) ; Default to :type/* if no mapping is found 91 | 92 | (defn- dbnames-set 93 | "Transform the string of databases to a set of strings." 94 | [dbnames] 95 | (when dbnames 96 | (set (map #(s/trim %) (s/split (s/trim dbnames) #","))))) 97 | 98 | (defn- jdbc-fields-metadata 99 | "Fetch metadata about the Fields belonging to a Table or View using a SELECT * query." 100 | [driver ^Connection conn db-name-or-nil schema table-name] 101 | (try 102 | (let [sql (str "SELECT * FROM " (when schema (str schema ".")) table-name " WHERE 1=0")] ; Query with no rows 103 | (with-open [stmt (.createStatement conn) 104 | rs (.executeQuery stmt sql)] 105 | (let [metadata (.getMetaData rs)] 106 | (mapv (fn [i] 107 | (let [column-name (.getColumnName metadata i) 108 | database-type (.getColumnTypeName metadata i) 109 | column-size (.getColumnDisplaySize metadata i) 110 | nullable (.isNullable metadata i) 111 | remarks (.getColumnLabel metadata i)] 112 | {:name column-name 113 | :database-type database-type 114 | :column-size column-size 115 | :nullable? (= nullable DatabaseMetaData/columnNullable) 116 | :remarks remarks})) 117 | (range 1 (inc (.getColumnCount metadata))))))) 118 | (catch java.sql.SQLException e 119 | (let [sqlstate (.getSQLState e)] 120 | (cond 121 | ;; 42S02: base object gone 122 | (= "42S02" sqlstate) 123 | (do 124 | (log/warn (trs "Table or view ''{0}'' in schema ''{1}'' does not exist." table-name schema)) 125 | []) 126 | ;; 42S22: column(s) referenced by the view no longer exist 127 | (= "42S22" sqlstate) 128 | (do 129 | (log/warn (trs "Skipping fields sync for ''{0}'' in schema ''{1}'' due to missing column(s). Cause: {2}" 130 | table-name schema (.getMessage e))) 131 | []) 132 | :else 133 | (throw e)))))) ; Re-throw other exceptions 134 | 135 | (defn ^:private fields-metadata 136 | [driver ^Connection conn {schema :schema, table-name :name} ^String db-name-or-nil] 137 | {:pre [(instance? Connection conn) (string? table-name)]} 138 | ;; Attempt to fetch metadata using DatabaseMetaData.getColumns 139 | (let [jdbc-metadata (jdbc-fields-metadata driver conn db-name-or-nil schema table-name)] 140 | jdbc-metadata)) 141 | 142 | (defmethod sql-jdbc.describe-table/describe-table-fields :teradata 143 | [driver conn table db-name-or-nil] 144 | (into 145 | #{} 146 | (sql-jdbc.describe-table/describe-table-fields-xf driver table) 147 | (fields-metadata driver conn table db-name-or-nil))) 148 | 149 | (defn- teradata-spec 150 | "Create a database specification for a Teradata database." 151 | [{:keys [host user password port dbnames charset tmode encrypt-data ssl additional-options] 152 | :or {host "localhost", charset "UTF8", tmode "ANSI", encrypt-data true, ssl false} 153 | :as opts}] 154 | (merge {:classname "com.teradata.jdbc.TeraDriver" 155 | :subprotocol "teradata" 156 | :subname (str "//" host "/" 157 | (->> (merge 158 | (when dbnames 159 | {"DATABASE" (first (dbnames-set dbnames))}) 160 | (when port 161 | {"DBS_PORT" port}) 162 | {"CHARSET" charset 163 | "TMODE" tmode 164 | "ENCRYPTDATA" (if encrypt-data "ON" "OFF") 165 | "FINALIZE_AUTO_CLOSE" "ON" 166 | "LOB_SUPPORT" "OFF"} 167 | (if ssl 168 | {"SSLMODE" "REQUIRE"})) 169 | (map #(format "%s=%s" (first %) (second %))) 170 | (clojure.string/join ",")))} 171 | (dissoc opts :host :port :dbnames :tmode :charset :ssl :encrypt-data))) 172 | 173 | (defmethod sql-jdbc.conn/connection-details->spec :teradata 174 | [_ details-map] 175 | (-> 176 | ;; :engine, :let-user-control-scheduling and :advanced-options are part of the details-map but would lead to 177 | ;; java.sql.SQLException: [Teradata JDBC Driver] [TeraJDBC 17.10.00.27] [Error 1536] [SQLState HY000] Invalid connection parameter name advanced-options 178 | ;; thus we filtering the map, using only the data we are interested in teradata-spec 179 | ;; (more keys might be added in the future to `default-advanced-options` => see metabase-plugin.yaml 180 | ;; thus we switched from using `dissoc` to `select-keys`) 181 | (select-keys details-map [:host :port :user :password :dbnames :charset :tmode :encrypt-data :ssl :additional-options]) 182 | teradata-spec 183 | (sql-jdbc.common/handle-additional-options details-map, :seperator-style :comma))) 184 | 185 | (defn- trunc [format-template v] 186 | [:trunc v (h2x/literal format-template)]) 187 | 188 | (def ^:private ^:const one-day [:raw "INTERVAL '1' DAY"]) 189 | 190 | (def ^:private ^:const now [:raw "CURRENT_TIMESTAMP"]) 191 | 192 | (defmethod sql.qp/date [:teradata :default] [_ _ expr] expr) 193 | (defmethod sql.qp/date [:teradata :minute] [_ _ expr] (:to_timestamp (:raw "'yyyy-mm-dd hh24:mi'") expr)) 194 | (defmethod sql.qp/date [:teradata :minute-of-hour] [_ _ expr] [::h2x/extract :minute expr]) 195 | (defmethod sql.qp/date [:teradata :hour] [_ _ expr] (:to_timestamp (:raw "'yyyy-mm-dd hh24'") expr)) 196 | (defmethod sql.qp/date [:teradata :hour-of-day] [_ _ expr] [::h2x/extract :hour expr]) 197 | (defmethod sql.qp/date [:teradata :day] [_ _ expr] (h2x/->date expr)) 198 | (defmethod sql.qp/date [:teradata :day-of-week] [driver _ expr] (h2x/inc (h2x/- (sql.qp/date driver :day expr) 199 | (sql.qp/date driver :week expr)))) 200 | (defmethod sql.qp/date [:teradata :day-of-month] [_ _ expr] [::h2x/extract :day expr]) 201 | (defmethod sql.qp/date [:teradata :day-of-year] [driver _ expr] (h2x/inc (h2x/- (sql.qp/date driver :day expr) (trunc :year expr)))) 202 | (defmethod sql.qp/date [:teradata :week] [_ _ expr] (trunc :day expr)) ; Same behaviour as with Oracle. 203 | (defmethod sql.qp/date [:teradata :week-of-year] [_ _ expr] (h2x/inc (h2x// (h2x/- (trunc :iw expr) 204 | (trunc :iy expr)) 205 | 7))) 206 | (defmethod sql.qp/date [:teradata :month] [_ _ expr] (trunc :month expr)) 207 | (defmethod sql.qp/date [:teradata :month-of-year] [_ _ expr] [::h2x/extract :month expr]) 208 | (defmethod sql.qp/date [:teradata :quarter] [_ _ expr] (trunc :q expr)) 209 | (defmethod sql.qp/date [:teradata :quarter-of-year] [driver _ expr] (h2x// (h2x/+ (sql.qp/date driver :month-of-year (sql.qp/date driver :quarter expr)) 2) 3)) 210 | (defmethod sql.qp/date [:teradata :year] [_ _ expr] (trunc :year expr)) 211 | 212 | (defn- num-to-interval [unit amount] 213 | [:raw (format "INTERVAL '%d' %s" (int (Math/abs amount)) (name unit))]) 214 | 215 | (defmethod sql.qp/add-interval-honeysql-form :teradata [_ hsql-form amount unit] 216 | (let [op (if (>= amount 0) h2x/+ h2x/-)] 217 | (op (if (= unit :month) 218 | (trunc :month hsql-form) 219 | (h2x/->timestamp hsql-form)) 220 | (case unit 221 | :second (num-to-interval :second amount) 222 | :minute (num-to-interval :minute amount) 223 | :hour (num-to-interval :hour amount) 224 | :day (num-to-interval :day amount) 225 | :week (num-to-interval :day (* amount 7)) 226 | :month (num-to-interval :month amount) 227 | :quarter (num-to-interval :month (* amount 3)) 228 | :year (num-to-interval :year amount))))) 229 | 230 | (def ^:private timestamp-types 231 | #{"timestamp" "timestamp with time zone" "timestamp with local time zone"}) 232 | 233 | (defmethod sql.qp/unix-timestamp->honeysql [:teradata :seconds] [_ _ field-or-value] 234 | (:to_timestamp field-or-value)) 235 | 236 | (defmethod sql.qp/unix-timestamp->honeysql [:teradata :milliseconds] [_ _ field-or-value] 237 | (sql.qp/unix-timestamp->honeysql (h2x// field-or-value 1000) :seconds)) 238 | 239 | (defmethod sql.qp/apply-top-level-clause [:teradata :limit] 240 | [_ _ honeysql-form {value :limit}] 241 | (update honeysql-form :select deduplicateutil/deduplicate-identifiers)) 242 | 243 | (defmethod sql.qp/apply-top-level-clause [:teradata :page] [_ _ honeysql-form {{:keys [items page]} :page}] 244 | (assoc honeysql-form :offset (:raw (format "QUALIFY ROW_NUMBER() OVER (%s) BETWEEN %d AND %d" 245 | (first (format (select-keys honeysql-form [:order-by]) 246 | :allow-dashed-names? true 247 | :quoting :ansi)) 248 | (inc (* items (dec page))) 249 | (* items page))))) 250 | 251 | (def excluded-schemas 252 | #{"SystemFe" "SYSLIB" "LockLogShredder" "Sys_Calendar" "SYSBAR" "SYSUIF" 253 | "dbcmngr" "tdwm" "TDStats" "TDQCD" "SQLJ" "SysAdmin" "SYSSPATIAL" "DBC" "Crashdumps" "External_AP" "TDPUSER"}) 254 | 255 | (defmethod sql-jdbc.sync/excluded-schemas :teradata [_] 256 | excluded-schemas) 257 | 258 | ;; Teradata uses ByteInt with values `1`/`0` for boolean `TRUE`/`FALSE`. 259 | (defmethod sql.qp/->honeysql [:teradata Boolean] 260 | [_ bool] 261 | (if bool 1 0)) 262 | 263 | (defn- get-tables 264 | "Fetch a JDBC Metadata ResultSet of tables in the DB, optionally limited to ones belonging to a given schema." 265 | ^ResultSet [^DatabaseMetaData metadata, ^String schema-or-nil] 266 | (jdbc/result-set-seq (.getTables metadata nil schema-or-nil "%" ; tablePattern "%" = match all tables 267 | (into-array String ["TABLE", "VIEW", "FOREIGN TABLE"])))) 268 | 269 | (defn- fast-active-tables 270 | "Teradata, fast implementation of `fast-active-tables` to support inclusion list." 271 | [driver, ^DatabaseMetaData metadata, {{:keys [dbnames]} :details, :as database}] 272 | (let [all-schemas (set (map :table_schem (jdbc/result-set-seq (.getSchemas metadata)))) 273 | dbs (dbnames-set dbnames) 274 | schemas (if (empty? dbs) 275 | (set/difference all-schemas excluded-schemas) ; use default exclusion list 276 | (set/intersection all-schemas dbs))] ; use defined inclusion list 277 | (set (for [schema schemas 278 | table-name (mapv :table_name (get-tables metadata schema))] 279 | {:name table-name 280 | :schema schema})))) 281 | 282 | ;; Overridden to have access to the database with the configured property dbnames (inclusion list) 283 | ;; which will be used to filter the schemas. 284 | (defmethod driver/describe-database :teradata [driver database] 285 | (jdbc/with-db-metadata [metadata (sql-jdbc.conn/db->pooled-connection-spec database)] 286 | {:tables (fast-active-tables, driver, ^DatabaseMetaData metadata, database)})) 287 | 288 | ;; We can't use getObject(int, Class) as the underlying Resultset used by the Teradata jdbc driver is based on jdk6. 289 | (defmethod sql-jdbc.execute/read-column-thunk [:teradata Types/TIMESTAMP] 290 | [_ rs _ i] 291 | (fn [] 292 | (when-let [value (.getTimestamp rs i)] 293 | (.toLocalDateTime value)))) 294 | 295 | (defmethod sql-jdbc.execute/read-column-thunk [:teradata Types/TIMESTAMP_WITH_TIMEZONE] 296 | [_ rs _ i] 297 | (fn [] 298 | (when-let [value (.getString rs i)] 299 | (OffsetDateTime/parse value)))) 300 | 301 | (defmethod sql-jdbc.execute/read-column-thunk [:teradata Types/DATE] 302 | [_ rs _ i] 303 | (fn [] 304 | (when-let [value (.getDate rs i)] 305 | (.toLocalDate value)))) 306 | 307 | (defmethod sql-jdbc.execute/read-column-thunk [:teradata Types/TIME] 308 | [_ rs _ i] 309 | (fn [] 310 | (when-let [value (.getTime rs i)] 311 | (.toLocalTime value)))) 312 | 313 | (defmethod sql-jdbc.execute/read-column-thunk [:teradata Types/TIME_WITH_TIMEZONE] 314 | [_ rs _ i] 315 | (fn [] 316 | (when-let [value (.getTime rs i)] 317 | (OffsetTime/parse value)))) 318 | 319 | ;; TODO: use metabase.driver.sql-jdbc.execute.legacy-impl instead of re-implementing everything here 320 | (defmethod sql-jdbc.execute/set-parameter [:teradata OffsetDateTime] 321 | [_ ^PreparedStatement ps ^Integer i t] 322 | (let [cal (Calendar/getInstance (TimeZone/getTimeZone (t/zone-id t))) 323 | t (t/sql-timestamp t)] 324 | (.setTimestamp ps i t cal))) 325 | 326 | (defmethod sql-jdbc.execute/do-with-connection-with-options :redshift 327 | [driver db-or-id-or-spec options f] 328 | (sql-jdbc.execute/do-with-resolved-connection 329 | driver 330 | db-or-id-or-spec 331 | options 332 | (fn [^Connection conn] 333 | (when-not (sql-jdbc.execute/recursive-connection?) 334 | (sql-jdbc.execute/set-best-transaction-level! driver conn) 335 | (try 336 | (.setReadOnly conn true) 337 | (catch Throwable e 338 | (log/debug e (trs "Error setting connection to read-only")))) 339 | (try 340 | (.setHoldability conn ResultSet/CLOSE_CURSORS_AT_COMMIT) 341 | (catch Throwable e 342 | (log/debug e (trs "Error setting default holdability for connection"))))) 343 | (f conn)))) 344 | 345 | (defn- cleanup-query 346 | "Remove the OFFSET keyword." 347 | [query] 348 | (update-in query [:native :query] (fn [value] (s/replace value "OFFSET" "")))) 349 | 350 | (defmethod driver/execute-reducible-query :teradata 351 | [driver query context respond] 352 | ((get-method driver/execute-reducible-query :sql-jdbc) driver (cleanup-query query) context respond)) 353 | 354 | (defmethod sql.qp/current-datetime-honeysql-form :teradata [_] now) 355 | 356 | ;; Overridden to customise the C3P0 properties which can be used to avoid the high number of logins against Teradata 357 | ;; In case of such problem increase the value of acquireRetryDelay 358 | ;; https://github.com/metabase/metabase/blob/master/src/metabase/driver/sql_jdbc/connection.clj#L42 359 | ;; https://www.mchange.com/projects/c3p0/#acquireRetryDelay 360 | (defmethod sql-jdbc.conn/data-warehouse-connection-pool-properties :teradata 361 | [driver database] 362 | {"acquireRetryDelay" (or (config/config-int :mb-jdbc-c3po-acquire-retry-delay) 1000) 363 | "acquireIncrement" 1 364 | "maxIdleTime" (* 6 60 60) ; 6 hours 365 | "minPoolSize" 1 366 | "initialPoolSize" 1 367 | "maxPoolSize" (or (config/config-int :mb-jdbc-data-warehouse-max-connection-pool-size) 30) 368 | "testConnectionOnCheckout" true 369 | "maxIdleTimeExcessConnections" (* 5 60) 370 | "checkoutTimeout" 300000 ; 300 seconds (increase this if needed) 371 | "idleConnectionTestPeriod" 300 ; Test idle connections every 5 minutes 372 | "maxConnectionAge" (* 6 60 60) ; 6 hours 373 | " dataSourceName " (format " db-%d-%s-%s " (u/the-id database) (name driver) (->> database 374 | :details 375 | ((some-fn :db 376 | :dbname 377 | :sid 378 | :catalog))))}) 379 | 380 | -------------------------------------------------------------------------------- /test/metabase/driver/teradata_test.clj: -------------------------------------------------------------------------------- 1 | (ns metabase.driver.teradata-test 2 | (:require [expectations.clojure.test :refer [defexpect expect expecting]] 3 | [metabase.driver.sql-jdbc.connection :as sql-jdbc.conn])) 4 | 5 | (def result 6 | (sql-jdbc.conn/connection-details->spec :teradata {:host "localhost" 7 | :additional-options "CONNECT_FAILURE_TTL=300,ERROR_QUERY_INTERVAL=300000,RECONNECT_INTERVAL=300,COP=OFF,REDRIVE=0"})) 8 | 9 | (def hardcoded 10 | {:classname "com.teradata.jdbc.TeraDriver" 11 | :subprotocol "teradata" 12 | :subname "//localhost/CHARSET=UTF8,TMODE=ANSI,ENCRYPTDATA=ON,FINALIZE_AUTO_CLOSE=ON,LOB_SUPPORT=OFF,CONNECT_FAILURE_TTL=300,ERROR_QUERY_INTERVAL=300000,RECONNECT_INTERVAL=300,COP=OFF,REDRIVE=0"}) 13 | 14 | ;; Check that additional JDBC options are handled correctly. This is comma separated for Teradata. 15 | (defexpect db-test 16 | (expect 17 | hardcoded 18 | result)) -------------------------------------------------------------------------------- /test/metabase/test/data/teradata.clj: -------------------------------------------------------------------------------- 1 | (ns metabase.test.data.teradata 2 | (:require [clojure.java.jdbc :as jdbc] 3 | [metabase.driver.sql-jdbc.connection :as sql-jdbc.conn] 4 | [metabase.test.data 5 | [interface :as tx] 6 | [sql :as sql.tx] 7 | [sql-jdbc :as sql-jdbc.tx]] 8 | [metabase.test.data.sql-jdbc 9 | [execute :as execute] 10 | [load-data :as load-data]] 11 | [metabase.util :as u])) 12 | 13 | (sql-jdbc.tx/add-test-extensions! :teradata) 14 | 15 | (defmethod sql.tx/field-base-type->sql-type [:teradata :type/BigInteger] [_ _] "BIGINT") 16 | (defmethod sql.tx/field-base-type->sql-type [:teradata :type/Boolean] [_ _] "BYTEINT") 17 | (defmethod sql.tx/field-base-type->sql-type [:teradata :type/Date] [_ _] "DATE") 18 | (defmethod sql.tx/field-base-type->sql-type [:teradata :type/DateTime] [_ _] "TIMESTAMP") 19 | (defmethod sql.tx/field-base-type->sql-type [:teradata :type/Decimal] [_ _] "DECIMAL") 20 | (defmethod sql.tx/field-base-type->sql-type [:teradata :type/Float] [_ _] "FLOAT") 21 | (defmethod sql.tx/field-base-type->sql-type [:teradata :type/Integer] [_ _] "INTEGER") 22 | (defmethod sql.tx/field-base-type->sql-type [:teradata :type/Text] [_ _] "VARCHAR(2048)") 23 | (defmethod sql.tx/field-base-type->sql-type [:teradata :type/Time] [_ _] "TIME") 24 | 25 | ;; Tested using Teradata Express VM image. Set the host to the correct address if localhost does not work. 26 | (def ^:private connection-details 27 | (delay 28 | {:host (tx/db-test-env-var-or-throw :teradata :host "localhost") 29 | :user (tx/db-test-env-var-or-throw :teradata :user "dbc") 30 | :password (tx/db-test-env-var-or-throw :teradata :password "dbc")})) 31 | 32 | (defmethod tx/dbdef->connection-details :teradata [& _] @connection-details) 33 | 34 | (defmethod sql.tx/drop-table-if-exists-sql :teradata [_ {:keys [database-name]} {:keys [table-name]}] 35 | (format "DROP TABLE \"%s\".\"%s\"⅋" database-name table-name)) 36 | 37 | (defmethod sql.tx/create-db-sql :teradata [_ {:keys [database-name]}] 38 | (format "CREATE user \"%s\" AS password=\"%s\" perm=524288000 spool=524288000;" database-name database-name)) 39 | 40 | (defmethod sql.tx/drop-db-if-exists-sql :teradata [_ {:keys [database-name]}] 41 | (format "DELETE user \"%s\" ALL; DROP user \"%s\";" database-name database-name)) 42 | 43 | (defmethod sql.tx/qualified-name-components :teradata 44 | ([_ db-name] [db-name]) 45 | ([_ db-name table-name] [db-name table-name]) 46 | ([_ db-name table-name field-name] [db-name table-name field-name])) 47 | 48 | (defn- dbspec [& _] 49 | (sql-jdbc.conn/connection-details->spec :teradata @connection-details)) 50 | 51 | ;; TODO override execute to be able to suppress db/table does not exist error. 52 | 53 | (defmethod execute/execute-sql! :teradata [& args] 54 | (apply execute/sequentially-execute-sql! args)) 55 | 56 | (defmethod load-data/load-data! :teradata [& args] 57 | (apply load-data/load-data-one-at-a-time! args)) 58 | 59 | (defmethod sql.tx/pk-sql-type :teradata [_] 60 | "INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1 INCREMENT BY 1 MINVALUE -2147483647 MAXVALUE 2147483647 NO CYCLE)") 61 | --------------------------------------------------------------------------------