diff --git a/README.md b/README.md index 902ff2c..38edb4b 100644 --- a/README.md +++ b/README.md @@ -107,6 +107,18 @@ Clickhouse.connection.exists_table("events") => true ``` +You can even check table existance upon creation. + +```ruby +Clickhouse.connection.create_table("events") do |t| + t.if_not_exists + t.fixed_string :id, 16 + t.uint16 :year + t.date :date + t.date_time :time + t.string :event +``` + Insert data. ```ruby diff --git a/lib/clickhouse/connection/query/table.rb b/lib/clickhouse/connection/query/table.rb index 8a65f49..7099e9d 100644 --- a/lib/clickhouse/connection/query/table.rb +++ b/lib/clickhouse/connection/query/table.rb @@ -5,6 +5,7 @@ class Table def initialize(name) @name = name + @if_not_exists = false @columns = [] yield self end @@ -13,12 +14,20 @@ def engine(value) @engine = value end + def if_not_exists(value = true) + @if_not_exists = value + end + def to_sql raise Clickhouse::InvalidQueryError, "Missing table engine" unless @engine length = @columns.collect{|x| x[0].to_s.size}.max sql = [] - sql << "CREATE TABLE #{@name} (" + if @if_not_exists + sql << "CREATE TABLE IF NOT EXISTS #{@name} (" + else + sql << "CREATE TABLE #{@name} (" + end @columns.each_with_index do |(name, type), index| sql << " #{name.ljust(length, " ")} #{type}#{"," unless index == @columns.size - 1}" diff --git a/test/unit/connection/query/test_table.rb b/test/unit/connection/query/test_table.rb index c5f606c..cda53be 100644 --- a/test/unit/connection/query/test_table.rb +++ b/test/unit/connection/query/test_table.rb @@ -17,16 +17,43 @@ class TestTable < MiniTest::Test t.engine "MergeTree(date, 8192)" end - sql = <<-SQL -CREATE TABLE logs_test ( - id UInt8, - price Float32, - name String, - date Date, - time DateTime, - hex_id FixedString(8) -) -ENGINE = MergeTree(date, 8192) + sql = <<~SQL + CREATE TABLE logs_test ( + id UInt8, + price Float32, + name String, + date Date, + time DateTime, + hex_id FixedString(8) + ) + ENGINE = MergeTree(date, 8192) + SQL + + assert_equal sql.strip, table.to_sql.strip + end + + it "generates a 'CREATE TABLE IF NOT EXISTS' statement" do + table = Clickhouse::Connection::Query::Table.new("logs_test") do |t| + t.if_not_exists + t.uint8 :id + t.float32 :price + t.string :name + t.date :date + t.date_time :time + t.fixed_string :hex_id, 8 + t.engine "MergeTree(date, 8192)" + end + + sql = <<~SQL + CREATE TABLE IF NOT EXISTS logs_test ( + id UInt8, + price Float32, + name String, + date Date, + time DateTime, + hex_id FixedString(8) + ) + ENGINE = MergeTree(date, 8192) SQL assert_equal sql.strip, table.to_sql.strip