├── test
├── pg_copy_tmp
│ └── .keep
├── kiba
│ ├── plus_test.rb
│ ├── plus
│ │ ├── helper_test.rb
│ │ ├── source
│ │ │ └── mysql_test.rb
│ │ └── destination
│ │ │ ├── csv_test.rb
│ │ │ ├── pg_test.rb
│ │ │ ├── mysql_test.rb
│ │ │ ├── pg_bulk_utils_test.rb
│ │ │ ├── pg_bulk2_test.rb
│ │ │ ├── mysql_bulk_test.rb
│ │ │ └── pg_bulk_test.rb
│ └── features
│ │ ├── mysql_to_x_test.rb
│ │ └── csv_to_x_test.rb
├── data
│ └── customer.csv
└── test_helper.rb
├── examples
├── sources
│ └── customer.rb
├── Gemfile
├── init.rb
├── data
│ └── customer.csv
├── customer_mysql_to_csv.etl
├── Gemfile.lock
├── customer_csv_to_pg.etl
├── customer_csv_to_mysql.etl
├── customer_mysql_to_pg.etl
└── incremental_insert.etl
├── lib
└── kiba
│ ├── plus
│ ├── version.rb
│ ├── logger.rb
│ ├── helper.rb
│ ├── source
│ │ ├── mysql.rb
│ │ └── pg.rb
│ ├── destination
│ │ ├── mysql.rb
│ │ ├── csv.rb
│ │ ├── pg.rb
│ │ ├── pg_bulk_utils.rb
│ │ ├── mysql_bulk.rb
│ │ ├── pg_bulk2.rb
│ │ └── pg_bulk.rb
│ └── job.rb
│ └── plus.rb
├── Gemfile
├── bin
├── setup
└── console
├── Rakefile
├── .travis.yml
├── .gitignore
├── LICENSE.txt
├── kiba-plus.gemspec
├── README.md
└── LICENSE
/test/pg_copy_tmp/.keep:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/examples/sources/customer.rb:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/lib/kiba/plus/version.rb:
--------------------------------------------------------------------------------
1 | module Kiba
2 | module Plus
3 | VERSION = "1.0.0"
4 | end
5 | end
6 |
--------------------------------------------------------------------------------
/examples/Gemfile:
--------------------------------------------------------------------------------
1 | source "https://rubygems.org"
2 |
3 | gem 'kiba-plus', :path => "../"
4 | gem 'pry'
5 |
--------------------------------------------------------------------------------
/Gemfile:
--------------------------------------------------------------------------------
1 | source 'https://rubygems.org'
2 |
3 | # Specify your gem's dependencies in kiba-plus.gemspec
4 | gemspec
5 | gem 'pg'
6 | gem 'mysql2'
7 |
--------------------------------------------------------------------------------
/bin/setup:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 | set -euo pipefail
3 | IFS=$'\n\t'
4 | set -vx
5 |
6 | bundle install
7 |
8 | # Do any other automated setup that you need to do here
9 |
--------------------------------------------------------------------------------
/test/kiba/plus_test.rb:
--------------------------------------------------------------------------------
1 | require 'test_helper'
2 |
3 | class Kiba::PlusTest < Minitest::Test
4 |
5 | def test_that_it_has_a_version_number
6 | refute_nil ::Kiba::Plus::VERSION
7 | end
8 |
9 | end
10 |
--------------------------------------------------------------------------------
/Rakefile:
--------------------------------------------------------------------------------
1 | require "bundler/gem_tasks"
2 | require "rake/testtask"
3 |
4 | Rake::TestTask.new(:test) do |t|
5 | t.libs << "test"
6 | t.libs << "lib"
7 | t.test_files = FileList['test/**/*_test.rb']
8 | end
9 |
10 | task :default => :spec
11 |
--------------------------------------------------------------------------------
/lib/kiba/plus/logger.rb:
--------------------------------------------------------------------------------
1 | require 'logger'
2 | module Kiba
3 | module Plus
4 | def self.logger
5 | @logger ||= Logger.new($stdout)
6 | end
7 |
8 | def self.logger=(logger)
9 | @logger = logger
10 | end
11 | end
12 | end
13 |
--------------------------------------------------------------------------------
/examples/init.rb:
--------------------------------------------------------------------------------
1 | Bundler.require(:default)
2 |
3 | include Kiba::Plus::Helper
4 |
5 | source_files = File.expand_path(File.dirname(__FILE__) + "/sources/*.rb")
6 | destination_files = File.expand_path(File.dirname(__FILE__) + "/destinations/*.rb")
7 |
8 | [source_files, destination_files].each do |files|
9 | Dir.glob(files).each {|f| require(f);puts "import #{f}"}
10 | end
--------------------------------------------------------------------------------
/bin/console:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env ruby
2 |
3 | require "bundler/setup"
4 | require "kiba/plus"
5 |
6 | # You can add fixtures and/or initialization code here to make experimenting
7 | # with your gem easier. You can also use a different console, if you like.
8 |
9 | # (If you use this, don't forget to add pry to your Gemfile!)
10 | # require "pry"
11 | # Pry.start
12 |
13 | require "irb"
14 | IRB.start
15 |
--------------------------------------------------------------------------------
/test/data/customer.csv:
--------------------------------------------------------------------------------
1 | 224862,hello@excite.com,hooopo,Wang
2 | 251732,hello@hotmail.ca,hooopo,Wang
3 | 30797,hello@excite.com,hooopo,Wang
4 | 59629,hello@rogers.com,hooopo,Wang
5 | 133665,"hello@live.ca",hooopo,Wang
6 | 199481,"hello@acanac.net",hooopo,Wang
7 | 288980,hello@gmail.com,hooopo,Wang
8 | 147067,hello@qc.aira.com,hooopo,Wang
9 | 339972,hello@nahlene.com,hooopo,Wang
10 | 307171,hello@gmail.com,hooopo,Wang
--------------------------------------------------------------------------------
/examples/data/customer.csv:
--------------------------------------------------------------------------------
1 | 224862,hello@excite.com,hooopo,Wang
2 | 251732,hello@hotmail.ca,hooopo,Wang
3 | 30797,hello@excite.com,hooopo,Wang
4 | 59629,hello@rogers.com,hooopo,Wang
5 | 133665,"hello@live.ca",hooopo,Wang
6 | 199481,"hello@acanac.net",hooopo,Wang
7 | 288980,hello@gmail.com,hooopo,Wang
8 | 147067,hello@qc.aira.com,hooopo,Wang
9 | 339972,hello@nahlene.com,hooopo,Wang
10 | 307171,hello@gmail.com,hooopo,Wang
--------------------------------------------------------------------------------
/lib/kiba/plus.rb:
--------------------------------------------------------------------------------
1 | require_relative "plus/version"
2 | require_relative "plus/helper"
3 |
4 | require_relative 'plus/logger'
5 |
6 | module Kiba
7 | module Plus
8 | end
9 | end
10 |
11 | class Hash
12 | def assert_valid_keys(*valid_keys)
13 | valid_keys.flatten!
14 | each_key do |k|
15 | unless valid_keys.include?(k)
16 | raise ArgumentError.new("Unknown key: #{k.inspect}. Valid keys are: #{valid_keys.map(&:inspect).join(', ')}")
17 | end
18 | end
19 | end
20 | end
21 |
--------------------------------------------------------------------------------
/examples/customer_mysql_to_csv.etl:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env ruby
2 | require_relative 'init'
3 |
4 | require 'kiba/plus/source/mysql'
5 | require 'kiba/plus/destination/csv'
6 |
7 | SOURCE_URL = 'mysql://root@localhost/shopperplus'
8 |
9 | source Kiba::Plus::Source::Mysql, :connect_url => SOURCE_URL,
10 | :query => %Q{SELECT id, email, 'hooopo' AS first_name, 'Wang' AS last_name FROM customers}
11 |
12 | destination Kiba::Plus::Destination::Csv, :output_file => "/tmp/customer_csv.csv"
13 |
14 | post_process do
15 | puts %x{head -n 10 /tmp/customer_csv.csv}
16 | end
17 |
--------------------------------------------------------------------------------
/examples/Gemfile.lock:
--------------------------------------------------------------------------------
1 | PATH
2 | remote: ../
3 | specs:
4 | kiba-plus (0.1.2)
5 | kiba (~> 0.6)
6 | mysql2 (~> 0.4)
7 | pg (~> 0.18)
8 |
9 | GEM
10 | remote: https://rubygems.org/
11 | specs:
12 | coderay (1.1.1)
13 | kiba (0.6.1)
14 | method_source (0.8.2)
15 | mysql2 (0.4.4)
16 | pg (0.18.4)
17 | pry (0.10.3)
18 | coderay (~> 1.1.0)
19 | method_source (~> 0.8.1)
20 | slop (~> 3.4)
21 | slop (3.6.0)
22 |
23 | PLATFORMS
24 | ruby
25 |
26 | DEPENDENCIES
27 | kiba-plus!
28 | pry
29 |
30 | BUNDLED WITH
31 | 1.11.2
32 |
--------------------------------------------------------------------------------
/lib/kiba/plus/helper.rb:
--------------------------------------------------------------------------------
1 | require 'uri'
2 | module Kiba
3 | module Plus
4 | module Helper
5 | def mysql2_connect_hash(url)
6 | return url if url.is_a?(Hash)
7 |
8 | u = URI.parse(url)
9 | {
10 | host: u.host,
11 | port: u.port,
12 | username: u.user,
13 | password: u.password,
14 | database: u.path[1..-1]
15 | }
16 | end
17 |
18 | def scheme(url)
19 | u = URI.parse(url)
20 | u.scheme
21 | end
22 |
23 | def format_sql(sql)
24 | sql.to_s.gsub(/[\n][\s]*[\n]/, "\n")
25 | end
26 |
27 | end
28 | end
29 | end
30 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: ruby
2 |
3 | rvm:
4 | - 2.2.4
5 |
6 | services:
7 | - mysql
8 | - postgresql
9 |
10 | env:
11 | - MYSQL2_SRC_CONNECT_URL=mysql2://travis@localhost/kiba_plus_src_test
12 | - MYSQL2_DEST_CONNECT_URL=mysql2://travis@localhost/kiba_plus_dest_test
13 | - PG_SRC_CONNECT_URL=postgresql://postgres@localhost/kiba_plus_src_test
14 | - PG_DEST_CONNECT_URL=postgresql://postgres@localhost/kiba_plus_dest_test
15 |
16 | before_install:
17 | - gem install bundler -v 1.11.2
18 |
19 | before_script:
20 | - mysql -e 'create database kiba_plus_src_test;'
21 | - mysql -e 'create database kiba_plus_dest_test;'
22 | - psql -c 'create database kiba_plus_src_test;' -U postgres
23 | - psql -c 'create database kiba_plus_dest_test;' -U postgres
24 |
25 | script: bundle exec rake test
26 |
--------------------------------------------------------------------------------
/examples/customer_csv_to_pg.etl:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env ruby
2 | require_relative 'init'
3 |
4 | require 'kiba/plus/destination/pg_bulk'
5 |
6 | DEST_URL = 'postgresql://hooopo@localhost:5432/crm2_dev'
7 |
8 | destination Kiba::Plus::Destination::PgBulk, { :connect_url => DEST_URL,
9 | :table_name => "customers",
10 | :input_file => File.expand_path(File.dirname(__FILE__) + "/data/customer.csv"),
11 | :truncate => true,
12 | :columns => [:id, :email, :first_name, :last_name],
13 | :incremental => false
14 | }
15 | post_process do
16 | result = PG.connect(DEST_URL).query("SELECT COUNT(*) AS num FROM customers")
17 | puts "Insert total: #{result.first['num']}"
18 | end
--------------------------------------------------------------------------------
/examples/customer_csv_to_mysql.etl:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env ruby
2 | require_relative 'init'
3 |
4 | require 'kiba/plus/destination/mysql_bulk'
5 |
6 | DEST_URL = 'mysql://root@localhost/crm2_dev'
7 |
8 | destination Kiba::Plus::Destination::MysqlBulk, { :connect_url => DEST_URL,
9 | :table_name => "customers",
10 | :input_file => File.expand_path(File.dirname(__FILE__) + "/data/customer.csv"),
11 | :truncate => true,
12 | :columns => [:id, :email, :first_name, :last_name],
13 | :incremental => false
14 | }
15 | post_process do
16 | result = Mysql2::Client.new(mysql2_connect_hash(DEST_URL)).query("SELECT COUNT(*) AS num FROM customers")
17 | puts "Insert total: #{result.first['num']}"
18 | end
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | /.bundle/
2 | /.yardoc
3 | /Gemfile.lock
4 | /_yardoc/
5 | /coverage/
6 | /doc/
7 | /pkg/
8 | /spec/reports/
9 | /tmp/
10 | *.gem
11 | *.rbc
12 | /.config
13 | /coverage/
14 | /InstalledFiles
15 | /pkg/
16 | /spec/reports/
17 | /spec/examples.txt
18 | /test/tmp/
19 | /test/version_tmp/
20 |
21 | ## Specific to RubyMotion:
22 | .dat*
23 | .repl_history
24 | build/
25 |
26 | ## Documentation cache and generated files:
27 | /.yardoc/
28 | /_yardoc/
29 | /doc/
30 | /rdoc/
31 |
32 | ## Environment normalization:
33 | /.bundle/
34 | /vendor/bundle
35 | /lib/bundler/man/
36 |
37 | # for a library or gem, you might want to ignore these files since the code is
38 | # intended to run in multiple environments; otherwise, check them in:
39 | # Gemfile.lock
40 | # .ruby-version
41 | # .ruby-gemset
42 |
43 | # unless supporting rvm < 1.11.0 or doing something fancy, ignore this:
44 | .rvmrc
45 |
46 | /test/pg_copy_tmp/*
47 | !/test/pg_copy_tmp/.keep
48 |
--------------------------------------------------------------------------------
/lib/kiba/plus/source/mysql.rb:
--------------------------------------------------------------------------------
1 | begin
2 | require 'mysql2'
3 | rescue LoadError
4 | puts 'gem mysql2 first!'
5 | end
6 | require 'uri'
7 |
8 | module Kiba
9 | module Plus::Source
10 | class Mysql
11 | include Kiba::Plus::Helper
12 | attr_reader :options, :client
13 |
14 | def initialize(options = {})
15 | @options = options
16 | @options.assert_valid_keys(
17 | :connect_url,
18 | :query
19 | )
20 | @client = Mysql2::Client.new(mysql2_connect_hash(connect_url))
21 | end
22 |
23 | def each
24 | Kiba::Plus.logger.info query
25 | results = client.query(query, as: :hash, symbolize_keys: true, stream: true, cache_rows: false)
26 | results.each do |row|
27 | yield(row)
28 | end
29 | end
30 |
31 | private
32 |
33 | def connect_url
34 | options.fetch(:connect_url)
35 | end
36 |
37 | def query
38 | options.fetch(:query)
39 | end
40 | end
41 | end
42 | end
43 |
--------------------------------------------------------------------------------
/LICENSE.txt:
--------------------------------------------------------------------------------
1 | The MIT License (MIT)
2 |
3 | Copyright (c) 2016 Hooopo
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in
13 | all copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21 | THE SOFTWARE.
22 |
--------------------------------------------------------------------------------
/lib/kiba/plus/destination/mysql.rb:
--------------------------------------------------------------------------------
1 | begin
2 | require 'mysql2'
3 | rescue LoadError
4 | puts 'gem mysql2 first!'
5 | end
6 |
7 | module Kiba::Plus::Destination
8 | class Mysql
9 | include Kiba::Plus::Helper
10 | attr_reader :options, :client
11 |
12 | def initialize(options = {})
13 | @options = options
14 | @options.assert_valid_keys(
15 | :connect_url,
16 | :prepare_sql,
17 | :columns
18 | )
19 | @client = Mysql2::Client.new(mysql2_connect_hash(connect_url))
20 | init
21 | end
22 |
23 | def write(row)
24 | @pre_stmt.execute(*row.values_at(*columns))
25 | rescue => e
26 | Kiba::Plus.logger.error "ERROR for #{row}"
27 | Kiba::Plus.logger.error e.message
28 | raise e
29 | end
30 |
31 | def close
32 | @client.close
33 | @client = nil
34 | end
35 |
36 | private
37 |
38 | def init
39 | @pre_stmt = @client.prepare(prepare_sql)
40 | end
41 |
42 | def connect_url
43 | options.fetch(:connect_url)
44 | end
45 |
46 | def prepare_sql
47 | options.fetch(:prepare_sql)
48 | end
49 |
50 | def columns
51 | options.fetch(:columns)
52 | end
53 | end
54 | end
55 |
--------------------------------------------------------------------------------
/lib/kiba/plus/destination/csv.rb:
--------------------------------------------------------------------------------
1 | require 'csv'
2 |
3 | module Kiba::Plus::Destination
4 | class Csv
5 | attr_reader :options, :csv
6 |
7 | def initialize(options = {})
8 | @options = options
9 | @options.assert_valid_keys(
10 | :output_file,
11 | :mode,
12 | :row_sep,
13 | :col_sep,
14 | :force_quotes,
15 | :quote_char
16 | )
17 | @csv = CSV.open(output_file, mode, {
18 | :col_sep => col_sep,
19 | :quote_char => quote_char,
20 | :force_quotes => force_quotes,
21 | :row_sep => row_sep
22 | })
23 | end
24 |
25 | def write(row)
26 | @csv << row.values
27 | end
28 |
29 | def close
30 | @csv.close
31 | end
32 |
33 | private
34 |
35 | def output_file
36 | options.fetch(:output_file)
37 | end
38 |
39 | def mode
40 | options.fetch(:mode, "w")
41 | end
42 |
43 | def row_sep
44 | options.fetch(:row_sep, "\n")
45 | end
46 |
47 | def col_sep
48 | options.fetch(:col_sep, ",")
49 | end
50 |
51 | def force_quotes
52 | options.fetch(:force_quotes, false)
53 | end
54 |
55 | def quote_char
56 | options.fetch(:quote_char, '"')
57 | end
58 |
59 | end
60 | end
61 |
--------------------------------------------------------------------------------
/examples/customer_mysql_to_pg.etl:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env ruby
2 | require_relative 'init'
3 |
4 | require 'kiba/plus/source/mysql'
5 | require 'kiba/plus/destination/pg_bulk2'
6 |
7 | SOURCE_URL = 'mysql://root@localhost/shopperplus'
8 |
9 | DEST_URL = 'postgresql://hooopo@localhost:5432/crm2_dev'
10 |
11 | source Kiba::Plus::Source::Mysql, { :connect_url => SOURCE_URL,
12 | :query => %Q{SELECT id, email, 'hooopo' AS first_name, 'Wang' AS last_name FROM customers}
13 | }
14 |
15 | destination Kiba::Plus::Destination::PgBulk2, { :connect_url => DEST_URL,
16 | :table_name => "customers",
17 | :truncate => true,
18 | :columns => [:id, :email, :first_name, :last_name],
19 | :incremental => false
20 | }
21 |
22 | post_process do
23 | result = PG.connect(DEST_URL).query("SELECT COUNT(*) AS num FROM customers")
24 | puts "Insert total: #{result.first['num']}"
25 | end
26 |
27 | # Output:
28 | # I, [2016-05-16T01:53:36.832565 #87909] INFO -- : TRUNCATE TABLE customers;
29 | # I, [2016-05-16T01:53:36.841770 #87909] INFO -- : COPY customers (id, email, first_name, last_name) FROM STDIN WITH DELIMITER ',' NULL '\N' CSV
30 | # Insert total: 428972
--------------------------------------------------------------------------------
/test/kiba/plus/helper_test.rb:
--------------------------------------------------------------------------------
1 | require 'test_helper'
2 |
3 | class Kiba::Plus::HelperTest < Minitest::Test
4 |
5 | include Kiba::Plus::Helper
6 |
7 | def test_mysql2_connect_hash_with_simple_mysql2_connect_url
8 | expected = {
9 | host: 'localhost',
10 | username: 'root',
11 | password: nil,
12 | port: nil,
13 | database: 'kiba_plus_test'
14 | }
15 |
16 | url = 'mysql://root@localhost/kiba_plus_test'
17 | result = mysql2_connect_hash(url)
18 |
19 | assert_equal expected, result
20 | end
21 |
22 | def test_mysql2_connect_hash_with_full_mysql2_connect_url
23 | expected = {
24 | host: 'localhost',
25 | username: 'root',
26 | password: '123456',
27 | port: 3306,
28 | database: 'kiba_plus_test'
29 | }
30 |
31 | url = 'mysql://root:123456@localhost:3306/kiba_plus_test'
32 | result = mysql2_connect_hash(url)
33 |
34 | assert_equal expected, result
35 | end
36 |
37 | def test_scheme_with_valid_url
38 | expected = 'mock'
39 |
40 | url = 'mock://'
41 | result = scheme(url)
42 |
43 | assert_equal expected, result
44 | end
45 |
46 | def test_scheme_with_invalid_url
47 | url = 'example.com'
48 | result = scheme(url)
49 |
50 | assert_nil result
51 | end
52 |
53 | def test_format_sql
54 | # TODO
55 | end
56 |
57 |
58 | end
59 |
--------------------------------------------------------------------------------
/test/kiba/plus/source/mysql_test.rb:
--------------------------------------------------------------------------------
1 | require 'test_helper'
2 | require "kiba/plus/source/mysql"
3 |
4 | class Kiba::Plus::Source::MysqlTest < Minitest::Test
5 |
6 | def setup
7 | @options = {
8 | connect_url: @@connect_urls[:mysql2_src],
9 | query: 'select id, email from customers'
10 | }
11 |
12 | @obj = Kiba::Plus::Source::Mysql.new(@options)
13 | end
14 |
15 | def test_initialize_with_simple_options
16 | assert_instance_of Mysql2::Client, @obj.client
17 | assert_equal @options, @obj.options
18 | end
19 |
20 | def test_each
21 | src_db = @@sequel_dbs[:mysql2_src]
22 | src_db.create_table! :customers do
23 | primary_key :id
24 | column :email, String
25 | end
26 | 1.upto(10).each do |n|
27 | src_db[:customers].insert id: n, email: "user#{n}@example.com"
28 | end
29 |
30 | rows = []
31 | @obj.each{|row| rows << row}
32 |
33 | assert_equal 10, rows.count
34 | assert_equal 'user10@example.com', rows.last[:email]
35 | end
36 |
37 | def test_connect_url
38 | assert_equal @@connect_urls[:mysql2_src], @obj.send(:connect_url)
39 |
40 | @obj.options.delete :connect_url
41 | assert_raises (KeyError) { @obj.send(:connect_url) }
42 | end
43 |
44 | def test_query
45 | assert_equal 'select id, email from customers', @obj.send(:query)
46 |
47 | @obj.options.delete :query
48 | assert_raises (KeyError) { @obj.send(:query) }
49 | end
50 | end
51 |
--------------------------------------------------------------------------------
/lib/kiba/plus/destination/pg.rb:
--------------------------------------------------------------------------------
1 | begin
2 | require 'pg'
3 | rescue LoadError
4 | puts 'gem pg first!'
5 | exit
6 | end
7 |
8 | module Kiba::Plus::Destination
9 | class Pg
10 | attr_reader :options, :conn
11 |
12 | def initialize(options = {})
13 | @options = options
14 | @options.assert_valid_keys(
15 | :connect_url,
16 | :schema,
17 | :table_name,
18 | :columns
19 | )
20 | @conn = PG.connect(connect_url)
21 | @conn.exec "SET search_path TO %s" % [ options[:schema] ] if options[:schema]
22 | init
23 | end
24 |
25 | def write(row)
26 | @conn.exec_prepared(prepare_name,
27 | row.values_at(*columns))
28 | rescue PG::Error => ex
29 | Kiba::Plus.logger.error "ERROR for #{row}"
30 | Kiba::Plus.logger.error ex.message
31 | # Maybe, write to db table or file
32 | raise ex
33 | end
34 |
35 | def close
36 | @conn.close
37 | @conn = nil
38 | end
39 |
40 | private
41 |
42 | def init
43 | @conn.prepare(prepare_name, prepare_sql)
44 | end
45 |
46 | def connect_url
47 | options.fetch(:connect_url)
48 | end
49 |
50 | def table_name
51 | options.fetch(:table_name)
52 | end
53 |
54 | def prepare_name
55 | options.fetch(:prepare_name, table_name + "_stmt")
56 | end
57 |
58 | def prepare_sql
59 | sql = <<-SQL
60 | INSERT INTO #{table_name} (#{columns.join(', ') }) VALUES (#{columns.each_with_index.map { |_, i| "$#{i + 1}" }.join(', ')});
61 | SQL
62 | end
63 |
64 | def columns
65 | options.fetch(:columns)
66 | end
67 | end
68 | end
69 |
--------------------------------------------------------------------------------
/kiba-plus.gemspec:
--------------------------------------------------------------------------------
1 | # coding: utf-8
2 | lib = File.expand_path('../lib', __FILE__)
3 | $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4 | require 'kiba/plus/version'
5 |
6 | Gem::Specification.new do |spec|
7 | spec.name = "kiba-plus"
8 | spec.version = Kiba::Plus::VERSION
9 | spec.authors = ["Hooopo"]
10 | spec.email = ["hoooopo@gmail.com"]
11 |
12 | spec.summary = %q{Kiba enhancement for Ruby ETL}
13 | spec.description = %q{It connects to various data sources including relational, non-relational, and flat file, cloud services and HTTP resources. It has flexible load strategies including insert, bulk load and upsert.}
14 | spec.homepage = "https://github.com/hooopo/kiba-plus"
15 | spec.license = "MIT"
16 |
17 | # Prevent pushing this gem to RubyGems.org by setting 'allowed_push_host', or
18 | # delete this section to allow pushing this gem to any host.
19 | if spec.respond_to?(:metadata)
20 | spec.metadata['allowed_push_host'] = "https://rubygems.org"
21 | else
22 | raise "RubyGems 2.0 or newer is required to protect against public gem pushes."
23 | end
24 |
25 | spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
26 | spec.bindir = "exe"
27 | spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
28 | spec.require_paths = ["lib"]
29 |
30 | spec.add_runtime_dependency "kiba", "~> 2.0.0"
31 |
32 | spec.add_development_dependency "bundler"
33 | spec.add_development_dependency "rake", "~> 10.0"
34 | spec.add_development_dependency "minitest", "~> 5.0"
35 | spec.add_development_dependency 'database_cleaner', '~> 1.5.3'
36 | spec.add_development_dependency 'sequel', '~> 4.34'
37 | spec.add_development_dependency 'pry'
38 | end
39 |
--------------------------------------------------------------------------------
/lib/kiba/plus/destination/pg_bulk_utils.rb:
--------------------------------------------------------------------------------
1 | module Kiba::Plus::Destination
2 | module PgBulkUtils
3 |
4 | private
5 |
6 | def staging_table_name
7 | table_name + "_staging"
8 | end
9 |
10 | def create_staging_table
11 | sql = create_staging_table_sql
12 | Kiba::Plus.logger.info sql
13 | @conn.exec(sql)
14 | end
15 |
16 | def create_staging_table_sql
17 | sql = <<-SQL
18 | CREATE UNLOGGED TABLE IF NOT EXISTS #{staging_table_name} (
19 | LIKE #{table_name} INCLUDING DEFAULTS INCLUDING CONSTRAINTS INCLUDING INDEXES
20 | ) WITH (autovacuum_enabled = off)
21 | SQL
22 | format_sql sql
23 | end
24 |
25 | def drop_staging_table
26 | sql = drop_staging_table_sql
27 | Kiba::Plus.logger.info sql
28 | @conn.exec(sql) rescue nil
29 | end
30 |
31 | def drop_staging_table_sql
32 | sql = "DROP TABLE IF EXISTS #{staging_table_name}"
33 | format_sql sql
34 | end
35 |
36 | def truncate_target_table
37 | sql = truncate_target_table_sql
38 | Kiba::Plus.logger.info sql
39 | @conn.exec(sql)
40 | end
41 |
42 | def truncate_target_table_sql
43 | sql = "TRUNCATE TABLE #{table_name}"
44 | format_sql sql
45 | end
46 |
47 | def merge_to_target_table
48 | sql = merge_to_target_table_sql
49 | Kiba::Plus.logger.info sql
50 | @conn.exec(sql)
51 | end
52 |
53 | def merge_to_target_table_sql
54 | sets = columns.map{|x| "#{x} = excluded.#{x}" }.join(', ')
55 | sql = <<~SQL
56 | INSERT INTO #{table_name} (SELECT * FROM #{staging_table_name})
57 | ON CONFLICT (#{Array(unique_by).join(", ")})
58 | DO UPDATE SET #{sets}
59 | SQL
60 | format_sql sql
61 | end
62 |
63 | end
64 | end
65 |
--------------------------------------------------------------------------------
/lib/kiba/plus/source/pg.rb:
--------------------------------------------------------------------------------
1 | begin
2 | require 'pg'
3 | rescue LoadError
4 | puts 'gem pg first!'
5 | exit
6 | end
7 | require 'uri'
8 |
9 | module Kiba
10 | module Plus::Source
11 | class Pg
12 | include Kiba::Plus::Helper
13 | attr_reader :options, :client
14 |
15 | def initialize(options = {})
16 | @options = options
17 | @options.assert_valid_keys(
18 | :connect_url,
19 | :schema,
20 | :query,
21 | :stream,
22 | :process_bar
23 | )
24 | @client = PG.connect(connect_url)
25 | @client.exec "SET search_path TO %s" % [ options[:schema] ] if options[:schema]
26 | end
27 |
28 | def each
29 | Kiba::Plus.logger.info query
30 | if stream?
31 | # http://www.rubydoc.info/github/ged/ruby-pg/PG%2FConnection%3Aset_single_row_mode
32 | client.send_query(query)
33 | client.set_single_row_mode
34 | loop do
35 | res = client.get_result or break
36 | res.check
37 | res.each do |row|
38 | print_process_bar if process_bar?
39 | yield(row)
40 | end
41 | end
42 | else
43 | results = client.query(query)
44 | results.each do |row|
45 | print_process_bar if process_bar?
46 | yield(row)
47 | end
48 | end
49 | end
50 |
51 | private
52 |
53 | def connect_url
54 | options.fetch(:connect_url)
55 | end
56 |
57 | def query
58 | options.fetch(:query)
59 | end
60 |
61 | def stream?
62 | options.fetch(:stream, false)
63 | end
64 |
65 | def process_bar?
66 | options.fetch(:process_bar, true)
67 | end
68 |
69 | def print_process_bar
70 | @num ||= 1
71 | $stdout.print "." * @num
72 | $stdout.print "\r"
73 | $stdout.flush
74 | @num = @num + 1
75 | end
76 | end
77 | end
78 | end
79 |
--------------------------------------------------------------------------------
/examples/incremental_insert.etl:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env ruby
2 | require_relative 'init'
3 |
4 | require 'kiba/plus/job'
5 | require 'kiba/plus/source/mysql'
6 | require 'kiba/plus/destination/pg_bulk2'
7 |
8 | SOURCE_URL = 'mysql://root@localhost/shopperplus'
9 |
10 | DEST_URL = 'postgresql://hooopo@localhost:5432/crm2_dev'
11 |
12 | pre_process do
13 | @job_id = Kiba::Plus::Job.new(
14 | :connect_url => DEST_URL,
15 | :start_at => Time.now,
16 | :job_name => "customer"
17 | ).start
18 | end
19 |
20 | last_pull_at = Kiba::Plus::Job.new(
21 | :connect_url => DEST_URL,
22 | :job_name => "customer"
23 | ).last_pull_at
24 |
25 | source Kiba::Plus::Source::Mysql, { :connect_url => SOURCE_URL,
26 | :query => %Q{SELECT id, email, 'hooopo' AS first_name, 'Wang' AS last_name FROM customers WHERE updated_at > '#{last_pull_at.to_s}'},
27 | :last_pull_at => last_pull_at,
28 | :incremental => true
29 | }
30 |
31 | destination Kiba::Plus::Destination::PgBulk2, { :connect_url => DEST_URL,
32 | :table_name => "customers",
33 | :truncate => false,
34 | :columns => [:id, :email, :first_name, :last_name],
35 | :incremental => true,
36 | :unique_by => :id
37 | }
38 |
39 | post_process do
40 | Kiba::Plus::Job.new(
41 | :connect_url => DEST_URL,
42 | :job_id => @job_id,
43 | :job_name => "customer"
44 | ).complete
45 | result = PG.connect(DEST_URL).query("SELECT COUNT(*) AS num FROM customers")
46 | puts "Insert total: #{result.first['num']}"
47 | end
48 |
49 | # Output:
50 | # I, [2016-05-16T01:53:36.832565 #87909] INFO -- : TRUNCATE TABLE customers;
51 | # I, [2016-05-16T01:53:36.841770 #87909] INFO -- : COPY customers (id, email, first_name, last_name) FROM STDIN WITH DELIMITER ',' NULL '\N' CSV
52 | # Insert total: 428972
--------------------------------------------------------------------------------
/test/kiba/plus/destination/csv_test.rb:
--------------------------------------------------------------------------------
1 | require 'test_helper'
2 |
3 | require "kiba/plus/destination/csv"
4 |
5 | class Kiba::Plus::Destination::CsvTest < Minitest::Test
6 |
7 | def setup
8 | @csv_path = make_csv_file
9 |
10 | @options = {
11 | output_file: @csv_path
12 | }
13 |
14 | @obj = Kiba::Plus::Destination::Csv.new(@options)
15 | end
16 |
17 | def test_initialize
18 | assert_instance_of CSV, @obj.csv
19 | assert_equal @options, @obj.options
20 | end
21 |
22 |
23 | def test_write
24 | 1.upto(10).each do |n|
25 | @obj.write({id: n, email: "user#{n}@example.com"})
26 | end
27 |
28 | assert_equal false, @obj.csv.closed?
29 |
30 | @obj.csv.close
31 | csv_rows = CSV.read(@csv_path)
32 | assert_equal 10, csv_rows.size
33 | assert_equal 'user10@example.com', csv_rows.last[1]
34 | end
35 |
36 | def test_close
37 | @obj.close
38 |
39 | assert_equal true, @obj.csv.closed?
40 | end
41 |
42 | def test_output_file
43 | assert_equal @csv_path, @obj.send(:output_file)
44 |
45 | @obj.options.delete :output_file
46 | assert_raises (KeyError) { @obj.send(:output_file) }
47 | end
48 |
49 | def test_mode
50 | @obj.options.delete :mode
51 | assert_equal 'w', @obj.send(:mode)
52 |
53 | @obj.options[:mode] = 'w+'
54 | assert_equal 'w+', @obj.send(:mode)
55 | end
56 |
57 | def test_row_sep
58 | @obj.options.delete :row_sep
59 | assert_equal "\n", @obj.send(:row_sep)
60 |
61 | @obj.options[:row_sep] = "\r\n"
62 | assert_equal "\r\n", @obj.send(:row_sep)
63 | end
64 |
65 | def test_col_sep
66 | @obj.options.delete :col_sep
67 | assert_equal ',', @obj.send(:col_sep)
68 |
69 | @obj.options[:col_sep] = ' '
70 | assert_equal ' ', @obj.send(:col_sep)
71 | end
72 |
73 | def test_force_quotes
74 | @obj.options.delete :force_quotes
75 | assert_equal false, @obj.send(:force_quotes)
76 |
77 | @obj.options[:force_quotes] = true
78 | assert_equal true, @obj.send(:force_quotes)
79 | end
80 |
81 | def test_quote_char
82 | @obj.options.delete :quote_char
83 | assert_equal '"', @obj.send(:quote_char)
84 |
85 | @obj.options[:quote_char] = "'"
86 | assert_equal "'", @obj.send(:quote_char)
87 | end
88 |
89 | end
90 |
--------------------------------------------------------------------------------
/test/kiba/plus/destination/pg_test.rb:
--------------------------------------------------------------------------------
1 | require 'test_helper'
2 |
3 | require "kiba/plus/destination/pg"
4 |
5 | class Kiba::Plus::Destination::PgTest < Minitest::Test
6 |
7 |
8 | def before_setup
9 | super
10 |
11 | dest_pg_db = @@sequel_dbs[:pg_dest]
12 |
13 | if dest_pg_db.table_exists? :customers_staging
14 | dest_pg_db.drop_table :customers_staging
15 | end
16 | dest_pg_db.create_table! :customers do
17 | primary_key :id
18 | column :email, String
19 | column :first_name, String
20 | column :last_name, String
21 | end
22 |
23 | @dest_pg_db = dest_pg_db
24 | end
25 |
26 | def setup
27 | @options = {
28 | connect_url: @@connect_urls[:pg_dest],
29 | columns: [:id, :email, :first_name, :last_name],
30 | table_name: 'customers'
31 | }
32 |
33 | @obj = Kiba::Plus::Destination::Pg.new(@options)
34 | end
35 |
36 | def test_initialize
37 | assert_instance_of PG::Connection, @obj.conn
38 | assert_equal @options, @obj.options
39 | end
40 |
41 | def test_write_when_row_id_is_null
42 | exception = assert_raises (PG::Error) { @obj.write({id: nil}) }
43 |
44 | assert_match /null value in column "id"/, exception.message
45 | end
46 |
47 | def test_write_when_default
48 | row = {id: 1, email: "user1@example.com", first_name: 'foo', last_name: 'bar'}
49 | result = @obj.write(row)
50 |
51 | assert_instance_of PG::Result, result
52 |
53 | assert_equal 1, @dest_pg_db[:customers].count
54 | assert_equal 'user1@example.com', @dest_pg_db[:customers].order(:id).last[:email]
55 | end
56 |
57 | def test_write_when_twice
58 | row = {id: 1, email: "user1@example.com", first_name: 'foo', last_name: 'bar'}
59 | @obj.write(row)
60 |
61 | exception = assert_raises (PG::Error) { @obj.write(row) }
62 | assert_match %r{duplicate key value violates unique constraint "customers_pkey"}, exception.message
63 | end
64 |
65 | def test_close
66 | @obj.close
67 | assert_nil @obj.conn
68 | end
69 |
70 | def test_connect_url
71 | assert_equal @@connect_urls[:pg_dest], @obj.send(:connect_url)
72 |
73 | @obj.options.delete :connect_url
74 | assert_raises (KeyError) { @obj.send(:connect_url) }
75 | end
76 |
77 |
78 | def test_columns
79 | assert_equal [:id, :email, :first_name, :last_name], @obj.send(:columns)
80 |
81 | @obj.options.delete :columns
82 | assert_raises (KeyError) { @obj.send(:columns) }
83 | end
84 |
85 |
86 | end
87 |
--------------------------------------------------------------------------------
/test/kiba/plus/destination/mysql_test.rb:
--------------------------------------------------------------------------------
1 | require 'test_helper'
2 |
3 | require "kiba/plus/destination/mysql"
4 |
5 | class Kiba::Plus::Destination::MysqlTest < Minitest::Test
6 | def before_setup
7 | super
8 |
9 | dest_mysql2_db = @@sequel_dbs[:mysql2_dest]
10 |
11 | dest_mysql2_db.create_table! :customers do
12 | primary_key :id
13 | column :email, String
14 | column :first_name, String
15 | column :last_name, String
16 | end
17 |
18 | @dest_mysql2_db = dest_mysql2_db
19 | end
20 |
21 | def setup
22 | @options = {
23 | connect_url: @@connect_urls[:mysql2_dest],
24 | prepare_sql: 'INSERT INTO customers VALUES (?, ?, ?, ?)',
25 | columns: [:id, :email, :first_name, :last_name]
26 | }
27 |
28 | @obj = Kiba::Plus::Destination::Mysql.new(@options)
29 | end
30 |
31 | def test_initialize
32 | assert_instance_of Mysql2::Client, @obj.client
33 | assert_equal @options, @obj.options
34 | end
35 |
36 | def test_write_when_row_id_is_null
37 | @obj.write({id: nil})
38 |
39 | # TODO why eq 1 ?
40 | # assert_equal 0, @dest_mysql2_db[:customers].count
41 | end
42 |
43 | def test_write_when_default
44 | row = {id: 1, email: "user1@example.com", first_name: 'foo', last_name: 'bar'}
45 | result = @obj.write(row)
46 |
47 | assert_nil result
48 |
49 | assert_equal 1, @dest_mysql2_db[:customers].count
50 | assert_equal 'user1@example.com', @dest_mysql2_db[:customers].order(:id).last[:email]
51 | end
52 |
53 | def test_write_when_twice
54 | row = {id: 1, email: "user1@example.com", first_name: 'foo', last_name: 'bar'}
55 | @obj.write(row)
56 |
57 | exception = assert_raises (Mysql2::Error) { @obj.write(row) }
58 |
59 | assert_match %r{Duplicate entry '1' for key 'PRIMARY'}, exception.message
60 | end
61 |
62 | def test_close
63 | @obj.close
64 | assert_nil @obj.client
65 | end
66 |
67 | def test_connect_url
68 | assert_equal @@connect_urls[:mysql2_dest], @obj.send(:connect_url)
69 |
70 | @obj.options.delete :connect_url
71 | assert_raises (KeyError) { @obj.send(:connect_url) }
72 | end
73 |
74 | def test_prepare_sql
75 | assert_equal 'INSERT INTO customers VALUES (?, ?, ?, ?)', @obj.send(:prepare_sql)
76 |
77 | @obj.options.delete :prepare_sql
78 | assert_raises (KeyError) { @obj.send(:prepare_sql) }
79 | end
80 |
81 | def test_columns
82 | assert_equal [:id, :email, :first_name, :last_name], @obj.send(:columns)
83 |
84 | @obj.options.delete :columns
85 | assert_raises (KeyError) { @obj.send(:columns) }
86 | end
87 |
88 | end
89 |
--------------------------------------------------------------------------------
/test/test_helper.rb:
--------------------------------------------------------------------------------
1 | require 'kiba'
2 |
3 | $LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)
4 | require 'kiba/plus'
5 |
6 | require 'sequel'
7 | require 'database_cleaner'
8 | require 'pry'
9 |
10 | require 'fileutils'
11 | require 'tempfile'
12 | require 'csv'
13 |
14 | require 'minitest/autorun'
15 |
16 | module Minitest::MyPlugin
17 |
18 | @@connect_urls = {
19 | mysql2_src: (ENV['MYSQL2_SRC_CONNECT_URL'] || 'mysql2://root@localhost/kiba_plus_src_test'),
20 | mysql2_dest: (ENV['MYSQL2_DEST_CONNECT_URL'] || 'mysql2://root@localhost/kiba_plus_dest_test'),
21 | pg_src: (ENV['PG_SRC_CONNECT_URL'] || 'postgresql://postgres@localhost/kiba_plus_src_test'),
22 | pg_dest: (ENV['PG_DEST_CONNECT_URL'] || 'postgresql://postgres@localhost/kiba_plus_dest_test')
23 | }
24 |
25 | @@sequel_dbs = Hash[
26 | @@connect_urls.map do |k, connect_url|
27 | [k, Sequel.connect(connect_url)]
28 | end
29 | ]
30 |
31 | @@database_cleaners = []
32 | @@sequel_dbs.each do |k, sequel_db|
33 | @@database_cleaners << DatabaseCleaner::Base.new(:sequel, { connection: sequel_db })
34 | end
35 | @@database_cleaners.each { |cleaner| cleaner.strategy = :truncation }
36 |
37 | @@test_dir = File.expand_path('..', __FILE__)
38 |
39 | def self.included(base)
40 | base.class_variable_set(:@@connect_urls, @@connect_urls)
41 | base.class_variable_set(:@@sequel_dbs, @@sequel_dbs)
42 |
43 | base.class_variable_set(:@@test_dir, @@test_dir)
44 | end
45 |
46 | def before_setup
47 | super
48 |
49 | @@database_cleaners.each(&:start)
50 | end
51 |
52 | def after_teardown
53 | super
54 |
55 | @@database_cleaners.each(&:clean)
56 | end
57 |
58 | private
59 |
60 | def run_etl_content(etl_content)
61 | etl_path = make_etl_file etl_content
62 |
63 | Kiba.run Kiba.parse(etl_content, etl_path)
64 | end
65 |
66 | def make_etl_file(etl_content)
67 | FileUtils.mkdir_p etl_tmpdir
68 |
69 | file = Tempfile.new ['etl', '.etl'], etl_tmpdir
70 | file.write etl_content
71 | file.path
72 | end
73 |
74 | def make_csv_file
75 | FileUtils.mkdir_p csv_tmpdir
76 |
77 | file = Tempfile.new ['csv', '.csv'], csv_tmpdir
78 | file.path
79 | end
80 |
81 | def etl_tmpdir
82 | File.join(Dir.tmpdir, 'etl')
83 | end
84 |
85 | def csv_tmpdir
86 | File.join(Dir.tmpdir, 'csv')
87 | end
88 |
89 | def wrap_sql(sql)
90 | sql.to_s.gsub(/[\s]+/, ' ').strip
91 | end
92 |
93 | end
94 |
95 | class MiniTest::Test
96 |
97 | include Minitest::MyPlugin
98 |
99 | end
100 |
101 | module Kiba::Features
102 | end
103 |
104 | # disable log
105 | Kiba::Plus.logger = Logger.new('/dev/null')
106 |
--------------------------------------------------------------------------------
/test/kiba/features/mysql_to_x_test.rb:
--------------------------------------------------------------------------------
1 | require 'test_helper'
2 |
3 | class Kiba::Features::MysqlToXTest < Minitest::Test
4 |
5 | attr_reader :src_db, :src_url
6 | attr_reader :dest_pg_db, :dest_pg_url, :dest_csv_path
7 |
8 | def build
9 | @src_db = @@sequel_dbs[:mysql2_src]
10 | @src_url = @@connect_urls[:mysql2_src]
11 |
12 | @dest_pg_db = @@sequel_dbs[:pg_dest]
13 | @dest_pg_url = @@connect_urls[:pg_dest]
14 |
15 | @dest_csv_path = make_csv_file
16 |
17 | src_db.create_table! :customers do
18 | primary_key :id
19 | column :email, String
20 | end
21 | 1.upto(10).each do |n|
22 | src_db[:customers].insert id: n, email: "user#{n}@example.com"
23 | end
24 |
25 | if dest_pg_db.table_exists? :customers_staging
26 | dest_pg_db.drop_table :customers_staging
27 | end
28 | dest_pg_db.create_table! :customers do
29 | primary_key :id
30 | column :email, String
31 | column :first_name, String
32 | column :last_name, String
33 | end
34 | end
35 |
36 | def test_to_pg_with_examples_customer_mysql_to_pg
37 | build
38 |
39 | etl_content = <<-ETL
40 | require 'kiba/plus'
41 |
42 | SOURCE_URL = '#{src_url}'
43 | DEST_URL = '#{dest_pg_url}'
44 |
45 | source Kiba::Plus::Source::Mysql, { :connect_url => SOURCE_URL,
46 | :query => %Q{SELECT id, email, 'hooopo' AS first_name, 'Wang' AS last_name FROM customers}
47 | }
48 |
49 | destination Kiba::Plus::Destination::PgBulk2, { :connect_url => DEST_URL,
50 | :table_name => "customers",
51 | :truncate => true,
52 | :columns => [:id, :email, :first_name, :last_name],
53 | :incremental => false
54 | }
55 |
56 | post_process do
57 | end
58 | ETL
59 | run_etl_content etl_content
60 |
61 | assert_equal 10, dest_pg_db[:customers].count
62 | assert_equal 'user10@example.com', dest_pg_db[:customers].order(:id).last[:email]
63 | end
64 |
65 | def test_to_csv_with_examples_customer_mysql_to_csv
66 | build
67 |
68 | etl_content = <<-ETL
69 | require 'kiba/plus'
70 |
71 | SOURCE_URL = '#{src_url}'
72 |
73 | source Kiba::Plus::Source::Mysql, :connect_url => SOURCE_URL,
74 | :query => %Q{SELECT id, email, 'hooopo' AS first_name, 'Wang' AS last_name FROM customers}
75 |
76 | destination Kiba::Plus::Destination::Csv, :output_file => '#{dest_csv_path}'
77 |
78 |
79 | post_process do
80 | end
81 | ETL
82 | run_etl_content etl_content
83 |
84 | csv_rows = CSV.read(dest_csv_path)
85 |
86 | assert_equal 10, csv_rows.size
87 | assert_equal 'user10@example.com', csv_rows.last[1]
88 | end
89 |
90 | end
91 |
--------------------------------------------------------------------------------
/lib/kiba/plus/destination/mysql_bulk.rb:
--------------------------------------------------------------------------------
1 | begin
2 | require 'mysql2'
3 | rescue LoadError
4 | puts 'gem mysql2 first!'
5 | end
6 |
7 | module Kiba::Plus::Destination
8 | class MysqlBulk
9 | include Kiba::Plus::Helper
10 | attr_reader :options, :client
11 |
12 | def initialize(options = {})
13 | @options = options
14 | @options.assert_valid_keys(
15 | :connect_url,
16 | :table_name,
17 | :columns,
18 | :truncate,
19 | :incremental,
20 | :input_file,
21 | :ignore_input_file_header,
22 | :delimited_by,
23 | :enclosed_by,
24 | :ignore_lines
25 | )
26 |
27 | @client = Mysql2::Client.new(mysql2_connect_hash(connect_url).merge(local_infile: true))
28 | end
29 |
30 | def write(row)
31 | # blank!
32 | end
33 |
34 | def close
35 | if truncate
36 | sql = truncate_sql
37 | Kiba::Plus.logger.info sql
38 | client.query(sql)
39 | end
40 |
41 | sql = bulk_sql
42 | Kiba::Plus.logger.info sql
43 | client.query(sql)
44 |
45 | client.close
46 | @client = nil
47 | end
48 |
49 | private
50 |
51 | def connect_url
52 | options.fetch(:connect_url)
53 | end
54 |
55 | def table_name
56 | options.fetch(:table_name)
57 | end
58 |
59 | def columns
60 | options.fetch(:columns)
61 | end
62 |
63 | def truncate
64 | options.fetch(:truncate, false)
65 | end
66 |
67 | def incremental
68 | options.fetch(:incremental, true)
69 | end
70 |
71 | def input_file
72 | options.fetch(:input_file)
73 | end
74 |
75 | def ignore_input_file_header
76 | !!options.fetch(:ignore_input_file_header, false)
77 | end
78 |
79 | def delimited_by
80 | options.fetch(:delimited_by, ",")
81 | end
82 |
83 | def enclosed_by
84 | options.fetch(:enclosed_by, '"')
85 | end
86 |
87 | def ignore_lines
88 | options.fetch(:ignore_lines, 0).to_i
89 | end
90 |
91 | def real_ignore_lines
92 | lines = ignore_lines
93 | lines += 1 if ignore_input_file_header
94 | lines
95 | end
96 |
97 | def truncate_sql
98 | sql = "TRUNCATE TABLE #{table_name}"
99 | format_sql sql
100 | end
101 |
102 | def bulk_sql
103 | sql = <<-SQL
104 | LOAD DATA LOCAL INFILE '#{input_file}'
105 | REPLACE
106 | INTO TABLE #{table_name}
107 | FIELDS
108 | TERMINATED BY '#{delimited_by}'
109 | ENCLOSED BY '#{enclosed_by}'
110 | IGNORE #{real_ignore_lines} LINES
111 | (#{columns.join(',')})
112 | SQL
113 | format_sql sql
114 | end
115 |
116 | end
117 | end
118 |
--------------------------------------------------------------------------------
/lib/kiba/plus/destination/pg_bulk2.rb:
--------------------------------------------------------------------------------
1 | begin
2 | require 'pg'
3 | rescue LoadError
4 | puts 'gem pg first!'
5 | exit
6 | end
7 | require 'csv'
8 | require_relative 'pg_bulk_utils'
9 | module Kiba::Plus::Destination
10 | class PgBulk2
11 | include PgBulkUtils
12 | include Kiba::Plus::Helper
13 | attr_reader :options, :conn
14 |
15 | def initialize(options = {})
16 | @options = options
17 | @options.assert_valid_keys(
18 | :connect_url,
19 | :schema,
20 | :table_name,
21 | :columns,
22 | :truncate,
23 | :incremental,
24 | :unique_by
25 | )
26 |
27 | @conn = PG.connect(connect_url)
28 | @conn.exec "SET search_path TO %s" % [ options[:schema] ] if options[:schema]
29 | init
30 | end
31 |
32 | def write(row)
33 | begin
34 | @conn.put_copy_data CSV.generate_line(row.values_at(*columns))
35 | rescue Exception => err
36 | errmsg = "%s while copy data: %s" % [ err.class.name, err.message ]
37 | @conn.put_copy_end( errmsg )
38 | Kiba::Plus.logger.error @conn.get_result
39 | raise
40 | end
41 | end
42 |
43 | def close
44 | @conn.put_copy_end
45 | @conn.get_last_result
46 | if incremental
47 | merge_to_target_table
48 | drop_staging_table
49 | end
50 | rescue
51 | raise
52 | ensure
53 | @conn.close
54 | @conn = nil
55 | end
56 |
57 | private
58 |
59 | def init
60 | if truncate
61 | drop_staging_table
62 | truncate_target_table
63 | end
64 | if incremental
65 | drop_staging_table
66 | create_staging_table
67 | sql = bulk_sql_with_incremental
68 | else
69 | sql = bulk_sql_with_non_incremental
70 | end
71 | Kiba::Plus.logger.info sql
72 | @conn.exec(sql)
73 | end
74 |
75 | def connect_url
76 | options.fetch(:connect_url)
77 | end
78 |
79 | def table_name
80 | options.fetch(:table_name)
81 | end
82 |
83 | def columns
84 | options.fetch(:columns)
85 | end
86 |
87 | def truncate
88 | options.fetch(:truncate, false)
89 | end
90 |
91 | def incremental
92 | options.fetch(:incremental, true)
93 | end
94 |
95 | def unique_by
96 | options.fetch(:unique_by, :id)
97 | end
98 |
99 | def bulk_sql_with_incremental
100 | sql = <<-SQL
101 | COPY #{staging_table_name} (#{columns.join(', ')})
102 | FROM STDIN
103 | WITH
104 | DELIMITER ','
105 | NULL '\\N'
106 | CSV
107 | SQL
108 | format_sql sql
109 | end
110 |
111 | def bulk_sql_with_non_incremental
112 | sql = <<-SQL
113 | COPY #{table_name} (#{columns.join(', ')})
114 | FROM STDIN
115 | WITH
116 | DELIMITER ','
117 | NULL '\\N'
118 | CSV
119 | SQL
120 | format_sql sql
121 | end
122 |
123 | end
124 | end
125 |
--------------------------------------------------------------------------------
/lib/kiba/plus/destination/pg_bulk.rb:
--------------------------------------------------------------------------------
1 | require_relative 'pg_bulk_utils'
2 | module Kiba::Plus::Destination
3 | class PgBulk
4 | include PgBulkUtils
5 | include Kiba::Plus::Helper
6 | attr_reader :options, :conn
7 |
8 | def initialize(options = {})
9 | @options = options
10 | @options.assert_valid_keys(
11 | :connect_url,
12 | :schema,
13 | :table_name,
14 | :columns,
15 | :truncate,
16 | :incremental,
17 | :unique_by,
18 | :input_file,
19 | :ignore_input_file_header
20 | )
21 | @conn = PG.connect(connect_url)
22 | @conn.exec "SET search_path TO %s" % [ options[:schema] ] if options[:schema]
23 | init
24 | end
25 |
26 | def write(row)
27 | # blank!
28 | end
29 |
30 | def close
31 | if incremental
32 | drop_staging_table
33 | create_staging_table
34 | copy_to_staging_table
35 | merge_to_target_table
36 | drop_staging_table
37 | else
38 | copy_to_target_table
39 | end
40 | @conn.close
41 | @conn = nil
42 | end
43 |
44 | private
45 |
46 | def init
47 | if truncate
48 | drop_staging_table
49 | truncate_target_table
50 | end
51 | end
52 |
53 | def connect_url
54 | options.fetch(:connect_url)
55 | end
56 |
57 | def table_name
58 | options.fetch(:table_name)
59 | end
60 |
61 | def columns
62 | options.fetch(:columns)
63 | end
64 |
65 | def truncate
66 | options.fetch(:truncate, false)
67 | end
68 |
69 | def incremental
70 | options.fetch(:incremental, true)
71 | end
72 |
73 | def unique_by
74 | options.fetch(:unique_by, :id)
75 | end
76 |
77 | def input_file
78 | options.fetch(:input_file)
79 | end
80 |
81 | def ignore_input_file_header
82 | !!options.fetch(:ignore_input_file_header, false)
83 | end
84 |
85 | def copy_to_target_table
86 | sql = copy_to_target_table_sql
87 | Kiba::Plus.logger.info sql
88 | @conn.exec(sql)
89 | end
90 |
91 | def copy_to_staging_table
92 | sql = copy_to_staging_table_sql
93 | Kiba::Plus.logger.info sql
94 | @conn.exec(sql)
95 | end
96 |
97 | def copy_to_target_table_sql
98 | sql = <<-SQL
99 | COPY #{table_name} (#{columns.join(', ')})
100 | FROM '#{File.expand_path(input_file)}'
101 | WITH
102 | #{ignore_input_file_header ? 'HEADER' : ''}
103 | DELIMITER ','
104 | NULL '\\N'
105 | CSV
106 | SQL
107 |
108 | format_sql sql
109 | end
110 |
111 | def copy_to_staging_table_sql
112 | sql = <<-SQL
113 | COPY #{staging_table_name} (#{columns.join(', ')})
114 | FROM '#{File.expand_path(input_file)}'
115 | WITH
116 | #{ignore_input_file_header ? 'HEADER' : ''}
117 | DELIMITER ','
118 | NULL '\\N'
119 | CSV
120 | SQL
121 |
122 | format_sql sql
123 | end
124 |
125 | end
126 | end
127 |
--------------------------------------------------------------------------------
/test/kiba/plus/destination/pg_bulk_utils_test.rb:
--------------------------------------------------------------------------------
1 | require 'test_helper'
2 |
3 | class Kiba::Plus::Destination::PgBulkUtilsTest < Minitest::Test
4 |
5 | def setup
6 | @options = {
7 | connect_url: @@connect_urls[:pg_dest],
8 | table_name: 'customers',
9 | columns: [:id, :email, :first_name, :last_name],
10 | input_file: File.join(@@test_dir, 'data/customer.csv')
11 | }
12 |
13 | @obj = Kiba::Plus::Destination::PgBulk.new(@options)
14 | end
15 |
16 | def test_staging_table_name
17 | @obj.stub :table_name, 'customers' do
18 | assert_equal 'customers_staging', @obj.send(:staging_table_name)
19 | end
20 | end
21 |
22 | def test_create_staging_table
23 | @obj.stub :create_staging_table_sql, 'select now()' do
24 | assert_instance_of PG::Result, @obj.send(:create_staging_table)
25 | end
26 | end
27 |
28 | def test_drop_staging_table
29 | @obj.stub :drop_staging_table_sql, 'select now()' do
30 | assert_instance_of PG::Result, @obj.send(:drop_staging_table)
31 | end
32 | end
33 |
34 | def test_truncate_target_table
35 | @obj.stub :truncate_target_table_sql, 'select now()' do
36 | assert_instance_of PG::Result, @obj.send(:truncate_target_table)
37 | end
38 | end
39 |
40 | def test_merge_to_target_table
41 | @obj.stub :merge_to_target_table_sql, 'select now()' do
42 | assert_instance_of PG::Result, @obj.send(:merge_to_target_table)
43 | end
44 | end
45 |
46 | def test_create_staging_table_sql
47 | expected_sql = <<-SQL
48 | CREATE UNLOGGED TABLE IF NOT EXISTS customers_staging (
49 | LIKE customers INCLUDING DEFAULTS INCLUDING CONSTRAINTS INCLUDING INDEXES
50 | ) WITH (autovacuum_enabled = off)
51 | SQL
52 |
53 | @obj.stub :staging_table_name, 'customers_staging' do
54 | @obj.stub :table_name, 'customers' do
55 | sql = @obj.send(:create_staging_table_sql)
56 |
57 | assert_equal wrap_sql(expected_sql), wrap_sql(sql)
58 | end
59 | end
60 | end
61 |
62 | def test_drop_staging_table_sql
63 | expected_sql = <<-SQL
64 | DROP TABLE IF EXISTS customers_staging
65 | SQL
66 |
67 | @obj.stub :staging_table_name, 'customers_staging' do
68 | sql = @obj.send(:drop_staging_table_sql)
69 |
70 | assert_equal wrap_sql(expected_sql), wrap_sql(sql)
71 | end
72 | end
73 |
74 | def test_truncate_target_table_sql
75 | expected_sql = <<-SQL
76 | TRUNCATE TABLE customers
77 | SQL
78 |
79 | @obj.stub :table_name, 'customers' do
80 | sql = @obj.send(:truncate_target_table_sql)
81 |
82 | assert_equal wrap_sql(expected_sql), wrap_sql(sql)
83 | end
84 | end
85 |
86 | def test_merge_to_target_table_sql
87 | expected_sql = <<-SQL
88 | INSERT INTO customers
89 | (SELECT * FROM customers_staging)
90 | ON CONFLICT (id)
91 | DO UPDATE SET id = excluded.id, email = excluded.email, first_name = excluded.first_name, last_name = excluded.last_name
92 | SQL
93 |
94 | @obj.stub :staging_table_name, 'customers_staging' do
95 | @obj.stub :table_name, 'customers' do
96 | sql = @obj.send(:merge_to_target_table_sql)
97 |
98 | assert_equal wrap_sql(expected_sql), wrap_sql(sql)
99 | end
100 | end
101 | end
102 |
103 | end
--------------------------------------------------------------------------------
/test/kiba/plus/destination/pg_bulk2_test.rb:
--------------------------------------------------------------------------------
1 | require 'test_helper'
2 |
3 | require "kiba/plus/destination/pg_bulk2"
4 |
5 | class Kiba::Plus::Destination::PgBulk2Test < Minitest::Test
6 |
7 |
8 | def before_setup
9 | super
10 |
11 | dest_pg_db = @@sequel_dbs[:pg_dest]
12 |
13 | if dest_pg_db.table_exists? :customers_staging
14 | dest_pg_db.drop_table :customers_staging
15 | end
16 | dest_pg_db.create_table! :customers do
17 | primary_key :id
18 | column :email, String
19 | column :first_name, String
20 | column :last_name, String
21 | end
22 | end
23 |
24 | def setup
25 | @options = {
26 | connect_url: @@connect_urls[:pg_dest],
27 | table_name: 'customers',
28 | columns: [:id, :email, :first_name, :last_name]
29 | }
30 |
31 | @obj = Kiba::Plus::Destination::PgBulk2.new(@options)
32 | end
33 |
34 | def teardown
35 | super
36 |
37 | if @obj.conn
38 | @obj.conn.put_copy_end
39 | end
40 | end
41 |
42 | def test_initialize
43 | assert_instance_of PG::Connection, @obj.conn
44 | assert_equal @options, @obj.options
45 | end
46 |
47 |
48 | def test_write
49 | # TODO
50 | end
51 |
52 | def test_close
53 | # TODO
54 | end
55 |
56 | def test_connect_url
57 | assert_equal @@connect_urls[:pg_dest], @obj.send(:connect_url)
58 |
59 | @obj.options.delete :connect_url
60 | assert_raises (KeyError) { @obj.send(:connect_url) }
61 | end
62 |
63 | def test_table_name
64 | assert_equal 'customers', @obj.send(:table_name)
65 |
66 | @obj.options.delete :table_name
67 | assert_raises (KeyError) { @obj.send(:table_name) }
68 | end
69 |
70 | def test_columns
71 | assert_equal [:id, :email, :first_name, :last_name], @obj.send(:columns)
72 |
73 | @obj.options.delete :columns
74 | assert_raises (KeyError) { @obj.send(:columns) }
75 | end
76 |
77 | def test_truncate
78 | @obj.options.delete :truncate
79 | assert_equal false, @obj.send(:truncate)
80 |
81 | @obj.options[:truncate] = true
82 | assert_equal true, @obj.send(:truncate)
83 | end
84 |
85 | def test_incremental
86 | @obj.options.delete :incremental
87 | assert_equal true, @obj.send(:incremental)
88 |
89 | @obj.options[:incremental] = false
90 | assert_equal false, @obj.send(:incremental)
91 | end
92 |
93 | def test_unique_by
94 | @obj.options.delete :unique_by
95 | assert_equal :id, @obj.send(:unique_by)
96 |
97 | @obj.options[:unique_by] = :uuid
98 | assert_equal :uuid, @obj.send(:unique_by)
99 | end
100 |
101 |
102 | def test_bulk_sql_with_incremental
103 | expected_sql = <<-SQL
104 | COPY customers_staging (id, email, first_name, last_name)
105 | FROM STDIN
106 | WITH
107 | DELIMITER ','
108 | NULL '\\N'
109 | CSV
110 | SQL
111 |
112 | @obj.stub :staging_table_name, 'customers_staging' do
113 | sql = @obj.send(:bulk_sql_with_incremental)
114 |
115 | assert_equal wrap_sql(expected_sql), wrap_sql(sql)
116 | end
117 | end
118 |
119 | def test_bulk_sql_with_non_incremental
120 | expected_sql = <<-SQL
121 | COPY customers (id, email, first_name, last_name)
122 | FROM STDIN
123 | WITH
124 | DELIMITER ','
125 | NULL '\\N'
126 | CSV
127 | SQL
128 |
129 | @obj.stub :table_name, 'customers' do
130 | sql = @obj.send(:bulk_sql_with_non_incremental)
131 |
132 | assert_equal wrap_sql(expected_sql), wrap_sql(sql)
133 | end
134 | end
135 |
136 | end
137 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # kiba-plus
2 | Kiba enhancement for Ruby ETL. It connects to various data sources including relational, non-relational, and flat file, cloud services and HTTP resources. It has flexible load strategies including insert, bulk load and upsert.
3 |
4 | # Usage
5 |
6 | ```ruby
7 | # /tmp/customer_mysql_to_pg.etl
8 |
9 | require 'kiba/plus'
10 |
11 | require 'kiba/plus/source/mysql'
12 | require 'kiba/plus/destination/pg_bulk2'
13 |
14 | SOURCE_URL = 'mysql://root@localhost/shopperplus'
15 |
16 | DEST_URL = 'postgresql://hooopo@localhost:5432/crm2_dev'
17 |
18 | source Kiba::Plus::Source::Mysql, { :connect_url => SOURCE_URL,
19 | :query => %Q{SELECT id, email, 'hooopo' AS first_name, 'Wang' AS last_name FROM customers}
20 | }
21 |
22 | destination Kiba::Plus::Destination::PgBulk2, { :connect_url => DEST_URL,
23 | :table_name => "customers",
24 | :truncate => true,
25 | :columns => [:id, :email, :first_name, :last_name],
26 | :incremental => false
27 | }
28 |
29 | post_process do
30 | result = PG.connect(DEST_URL).query("SELECT COUNT(*) AS num FROM customers")
31 | puts "Insert total: #{result.first['num']}"
32 | end
33 | ```
34 |
35 | Execute in shell:
36 |
37 | ```shell
38 | $ bundle exec kiba /tmp/customer_mysql_to_pg.etl
39 |
40 | # Output:
41 | # I, [2016-05-16T01:53:36.832565 #87909] INFO -- : TRUNCATE TABLE customers;
42 | # I, [2016-05-16T01:53:36.841770 #87909] INFO -- : COPY customers (id, email, first_name, last_name) FROM STDIN WITH DELIMITER ',' NULL '\N' CSV
43 | # Insert total: 428972
44 | ```
45 |
46 | Execute in ruby script:
47 |
48 | ```ruby
49 | require 'kiba'
50 |
51 | job_definition = Kiba.parse(IO.read('/tmp/customer_mysql_to_pg.etl'), '/tmp/customer_mysql_to_pg.etl')
52 | Kiba.run(job_definition)
53 | ```
54 |
55 | # Examples
56 |
57 | * [CSV to MySQL](https://github.com/hooopo/kiba-plus/blob/master/examples/customer_csv_to_mysql.etl)
58 | * [CSV to PG](https://github.com/hooopo/kiba-plus/blob/master/examples/customer_csv_to_pg.etl)
59 | * [MySQL to CSV](https://github.com/hooopo/kiba-plus/blob/master/examples/customer_mysql_to_csv.etl)
60 | * [MySQL to PG](https://github.com/hooopo/kiba-plus/blob/master/examples/customer_mysql_to_pg.etl)
61 | * [MySQL incremental to PG](https://github.com/hooopo/kiba-plus/blob/master/examples/incremental_insert.etl)
62 |
63 | # Main Feature
64 |
65 | * Csv Source
66 | * MySQL Source
67 | * Postgresql Source
68 | * Citus Source
69 | * Greenplus Source
70 | * MongoDB Source (TODO)
71 | * Elastic Source (TODO)
72 | * Redshift Source (TODO)
73 |
74 | * Csv Destination
75 | * MySQL Destination
76 | * Postgresql Destination
77 | * Citus Destination
78 | * Greenplus Destination
79 | * MongoDB Destination (TODO)
80 | * Elastic Destination (TODO)
81 | * Redshift Destination (TODO)
82 |
83 | * Bulk Load for large dataset
84 | * Upsert for MySQL & Postgresql
85 | * Incremental Update
86 |
87 | ## Installation
88 |
89 | Add this line to your application's Gemfile:
90 |
91 | ```ruby
92 | gem 'kiba'
93 | gem 'kiba-plus'
94 | ```
95 |
96 | And then execute:
97 |
98 | $ bundle
99 |
100 | Or install it yourself as:
101 |
102 | $ gem install kiba-plus
103 |
104 | ## Development
105 |
106 | First of all, Please run the following code in shell.
107 |
108 | ```bash
109 |
110 | $ mysql -e 'create database kiba_plus_src_test;'
111 |
112 | $ mysql -e 'create database kiba_plus_dest_test;'
113 |
114 | $ psql -c 'create database kiba_plus_src_test;' -U postgres
115 |
116 | $ psql -c 'create database kiba_plus_dest_test;' -U postgres
117 |
118 | ```
119 |
120 | After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake test` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
121 |
122 | To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
123 |
124 | ## Contributing
125 |
126 | Bug reports and pull requests are welcome on GitHub at https://github.com/hooopo/kiba-plus.
127 |
--------------------------------------------------------------------------------
/test/kiba/plus/destination/mysql_bulk_test.rb:
--------------------------------------------------------------------------------
1 | require 'test_helper'
2 |
3 | require "kiba/plus/destination/mysql_bulk"
4 |
5 | class Kiba::Plus::Destination::MysqlBulkTest < Minitest::Test
6 |
7 | def setup
8 | @options = {
9 | connect_url: @@connect_urls[:mysql2_dest],
10 | table_name: 'customers',
11 | columns: [:id, :email, :first_name, :last_name],
12 | input_file: File.join(@@test_dir, 'data/customer.csv')
13 | }
14 |
15 | @obj = Kiba::Plus::Destination::MysqlBulk.new(@options)
16 | end
17 |
18 | def test_initialize
19 | assert_instance_of Mysql2::Client, @obj.client
20 | assert_equal @options, @obj.options
21 | end
22 |
23 | def test_write
24 | assert_nil @obj.write([])
25 | end
26 |
27 | def test_close_when_truncate
28 | @obj.stub :truncate, true do
29 | @obj.stub :truncate_sql, 'select now()' do
30 | @obj.stub :bulk_sql, 'select now()' do
31 | @obj.close
32 | assert_nil @obj.client
33 | end
34 | end
35 | end
36 | end
37 |
38 | def test_close_when_non_truncate
39 | @obj.stub :truncate, false do
40 | @obj.stub :bulk_sql, 'select now()' do
41 | @obj.close
42 | assert_nil @obj.client
43 | end
44 | end
45 | end
46 |
47 | def test_connect_url
48 | assert_equal @@connect_urls[:mysql2_dest], @obj.send(:connect_url)
49 |
50 | @obj.options.delete :connect_url
51 | assert_raises (KeyError) { @obj.send(:connect_url) }
52 | end
53 |
54 | def test_table_name
55 | assert_equal 'customers', @obj.send(:table_name)
56 |
57 | @obj.options.delete :table_name
58 | assert_raises (KeyError) { @obj.send(:table_name) }
59 | end
60 |
61 | def test_columns
62 | assert_equal [:id, :email, :first_name, :last_name], @obj.send(:columns)
63 |
64 | @obj.options.delete :columns
65 | assert_raises (KeyError) { @obj.send(:columns) }
66 | end
67 |
68 | def test_truncate
69 | @obj.options.delete :truncate
70 | assert_equal false, @obj.send(:truncate)
71 |
72 | @obj.options[:truncate] = true
73 | assert_equal true, @obj.send(:truncate)
74 | end
75 |
76 | def test_incremental
77 | @obj.options.delete :incremental
78 | assert_equal true, @obj.send(:incremental)
79 |
80 | @obj.options[:incremental] = false
81 | assert_equal false, @obj.send(:incremental)
82 | end
83 |
84 | def test_input_file
85 | assert_equal "#{@@test_dir}/data/customer.csv", @obj.send(:input_file)
86 |
87 | @obj.options.delete :input_file
88 | assert_raises (KeyError) { @obj.send(:input_file) }
89 | end
90 |
91 | def test_ignore_input_file_header
92 | @obj.options.delete :ignore_input_file_header
93 | assert_equal false, @obj.send(:ignore_input_file_header)
94 |
95 | @obj.options[:ignore_input_file_header] = true
96 | assert_equal true, @obj.send(:ignore_input_file_header)
97 | end
98 |
99 | def test_delimited_by
100 | @obj.options.delete :delimited_by
101 | assert_equal ',', @obj.send(:delimited_by)
102 |
103 | @obj.options[:delimited_by] = ' '
104 | assert_equal ' ', @obj.send(:delimited_by)
105 | end
106 |
107 | def test_enclosed_by
108 | @obj.options.delete :enclosed_by
109 | assert_equal '"', @obj.send(:enclosed_by)
110 |
111 | @obj.options[:enclosed_by] = '|'
112 | assert_equal '|', @obj.send(:enclosed_by)
113 | end
114 |
115 | def test_ignore_lines
116 | @obj.options.delete :ignore_lines
117 | assert_equal 0, @obj.send(:ignore_lines)
118 |
119 | @obj.options[:ignore_lines] = 1
120 | assert_equal 1, @obj.send(:ignore_lines)
121 | end
122 |
123 | def test_real_ignore_lines
124 | @obj.stub :ignore_lines, 1 do
125 | @obj.stub :ignore_input_file_header, false do
126 | assert_equal 1, @obj.send(:real_ignore_lines)
127 | end
128 | end
129 |
130 | @obj.stub :ignore_lines, 1 do
131 | @obj.stub :ignore_input_file_header, true do
132 | assert_equal 2, @obj.send(:real_ignore_lines)
133 | end
134 | end
135 | end
136 |
137 | def test_truncate_sql
138 | assert_equal 'TRUNCATE TABLE customers', @obj.send(:truncate_sql)
139 | end
140 |
141 | def test_bulk_sql
142 | expected_sql = <<-SQL
143 | LOAD DATA LOCAL INFILE '#{@@test_dir}/data/customer.csv'
144 | REPLACE
145 | INTO TABLE customers
146 | FIELDS
147 | TERMINATED BY ','
148 | ENCLOSED BY '"'
149 | IGNORE 1 LINES
150 | (id,email,first_name,last_name)
151 | SQL
152 |
153 | @obj.stub :real_ignore_lines, 1 do
154 | sql = @obj.send(:bulk_sql)
155 |
156 | assert_equal wrap_sql(expected_sql), wrap_sql(sql)
157 | end
158 | end
159 |
160 | end
161 |
--------------------------------------------------------------------------------
/lib/kiba/plus/job.rb:
--------------------------------------------------------------------------------
1 | require 'uri'
2 |
3 | module Kiba
4 | require 'uri'
5 |
6 | module Plus
7 | class Job
8 | include Kiba::Plus::Helper
9 |
10 | attr_reader :options, :client
11 | def initialize(options)
12 | @options = options
13 | @options.assert_valid_keys(:connect_url, :job_id, :job_name, :start_at, :completed_at, :schema, :job_table_name)
14 | url = URI.parse(connect_url)
15 | if url.scheme =~ /mysql/i
16 | @client = Mysql2::Client.new(mysql2_connect_hash(connect_url))
17 | elsif url.scheme =~ /postgres/i
18 | @client = PG.connect(connect_url)
19 | @client.exec "SET search_path TO %s" % [ options[:schema] ] if options[:schema]
20 | else
21 | raise 'No Imp!'
22 | end
23 | end
24 |
25 | def job_id
26 | options.fetch(:job_id, nil)
27 | end
28 |
29 | def connect_url
30 | options.fetch(:connect_url)
31 | end
32 |
33 | def job_name
34 | options.fetch(:job_name)
35 | end
36 |
37 | def job_table_name
38 | options.fetch(:job_table_name, "etl_jobs")
39 | end
40 |
41 | def start_at
42 | options.fetch(:start_at, Time.now)
43 | end
44 |
45 | def completed_at
46 | options.fetch(:completed_at, Time.now)
47 | end
48 |
49 | def start
50 | create_table
51 | result = create_job
52 | result.first["id"].to_i
53 | end
54 |
55 | def last_pull_at
56 | sql = "SELECT MAX(created_at) AS last_pull_at FROM #{job_table_name} WHERE status = 'completed' AND job_name = '#{job_name}'"
57 | Kiba::Plus.logger.info sql
58 | client.query(sql).first["last_pull_at"]
59 | end
60 |
61 | def complete
62 | complete_job
63 | end
64 |
65 | private
66 |
67 | def create_table
68 | url = URI.parse(connect_url)
69 | if url.scheme =~ /mysql/i
70 | create_table_mysql
71 | elsif url.scheme =~ /postgres/i
72 | create_table_pg
73 | else
74 | raise 'No Imp!'
75 | end
76 | end
77 |
78 | def create_job
79 | if defined?(Mysql2::Client) && @client.is_a?(Mysql2::Client)
80 | create_job_mysql
81 | else
82 | create_job_pg
83 | end
84 | end
85 |
86 | def create_job_mysql
87 | sql = <<-SQL
88 | INSERT INTO #{job_table_name} (
89 | completed_at,
90 | job_name,
91 | created_at,
92 | status) VALUES
93 | (NULL, '#{job_name}', '#{start_at.utc.strftime("%Y-%m-%dT%H:%M:%S.%L")}', 'executing')
94 | SQL
95 | Kiba::Plus.logger.info sql
96 | @client.query(sql)
97 | returning_id_sql = "SELECT LAST_INSERT_ID() AS id"
98 | Kiba::Plus.logger.info returning_id_sql
99 | @client.query(returning_id_sql)
100 | end
101 |
102 | def create_job_pg
103 | sql = <<-SQL
104 | INSERT INTO #{job_table_name} (
105 | completed_at,
106 | job_name,
107 | created_at,
108 | status) VALUES
109 | (NULL, '#{job_name}', '#{start_at.utc.strftime("%Y-%m-%dT%H:%M:%S.%L")}', 'executing') RETURNING id
110 | SQL
111 | Kiba::Plus.logger.info sql
112 | @client.query(sql)
113 | end
114 |
115 | def create_table_pg
116 | sql = <<-SQL
117 | CREATE TABLE IF NOT EXISTS #{job_table_name} (
118 | id SERIAL,
119 | job_name varchar(255) NOT NULL,
120 | created_at TIMESTAMP without time zone,
121 | completed_at TIMESTAMP without time zone,
122 | status varchar(255) DEFAULT NULL,
123 | PRIMARY KEY (id)
124 | )
125 | SQL
126 | Kiba::Plus.logger.info sql
127 | @client.query(sql)
128 | end
129 |
130 | def create_table_mysql
131 | sql = <<-SQL
132 | CREATE TABLE IF NOT EXISTS #{job_table_name} (
133 | id integer(11) NOT NULL AUTO_INCREMENT,
134 | job_name varchar(255) NOT NULL,
135 | created_at datetime NOT NULL,
136 | completed_at datetime DEFAULT NULL,
137 | status varchar(255) DEFAULT NULL,
138 | PRIMARY KEY (id)
139 | ) AUTO_INCREMENT=1
140 | SQL
141 | Kiba::Plus.logger.info sql
142 | @client.query(sql)
143 | end
144 |
145 | def complete_job
146 | sql = %Q/UPDATE #{job_table_name} SET status = 'completed', completed_at = '#{completed_at.utc.strftime("%Y-%m-%dT%H:%M:%S.%L")}' WHERE id = #{job_id} AND job_name = '#{job_name}'/
147 | Kiba::Plus.logger.info sql
148 | @client.query(sql)
149 | end
150 | end
151 | end
152 | end
153 |
--------------------------------------------------------------------------------
/test/kiba/plus/destination/pg_bulk_test.rb:
--------------------------------------------------------------------------------
1 | require 'test_helper'
2 |
3 | require "kiba/plus/destination/pg_bulk"
4 |
5 | class Kiba::Plus::Destination::PgBulkTest < Minitest::Test
6 |
7 | def before_setup
8 | super
9 |
10 | dest_pg_db = @@sequel_dbs[:pg_dest]
11 |
12 | if dest_pg_db.table_exists? :customers_staging
13 | dest_pg_db.drop_table :customers_staging
14 | end
15 | dest_pg_db.create_table! :customers do
16 | primary_key :id
17 | column :email, String
18 | column :first_name, String
19 | column :last_name, String
20 | end
21 | end
22 |
23 | def setup
24 | @options = {
25 | connect_url: @@connect_urls[:pg_dest],
26 | table_name: 'customers',
27 | columns: [:id, :email, :first_name, :last_name],
28 | input_file: File.join(@@test_dir, 'data/customer.csv')
29 | }
30 |
31 | @obj = Kiba::Plus::Destination::PgBulk.new(@options)
32 | end
33 |
34 | def test_initialize
35 | assert_instance_of PG::Connection, @obj.conn
36 | assert_equal @options, @obj.options
37 | end
38 |
39 | def test_write
40 | assert_nil @obj.write([])
41 | end
42 |
43 | def test_close
44 | # TODO
45 | end
46 |
47 | def test_connect_url
48 | assert_equal @@connect_urls[:pg_dest], @obj.send(:connect_url)
49 |
50 | @obj.options.delete :connect_url
51 | assert_raises (KeyError) { @obj.send(:connect_url) }
52 | end
53 |
54 | def test_table_name
55 | assert_equal 'customers', @obj.send(:table_name)
56 |
57 | @obj.options.delete :table_name
58 | assert_raises (KeyError) { @obj.send(:table_name) }
59 | end
60 |
61 | def test_columns
62 | assert_equal [:id, :email, :first_name, :last_name], @obj.send(:columns)
63 |
64 | @obj.options.delete :columns
65 | assert_raises (KeyError) { @obj.send(:columns) }
66 | end
67 |
68 | def test_truncate
69 | @obj.options.delete :truncate
70 | assert_equal false, @obj.send(:truncate)
71 |
72 | @obj.options[:truncate] = true
73 | assert_equal true, @obj.send(:truncate)
74 | end
75 |
76 | def test_incremental
77 | @obj.options.delete :incremental
78 | assert_equal true, @obj.send(:incremental)
79 |
80 | @obj.options[:incremental] = false
81 | assert_equal false, @obj.send(:incremental)
82 | end
83 |
84 | def test_unique_by
85 | @obj.options.delete :unique_by
86 | assert_equal :id, @obj.send(:unique_by)
87 |
88 | @obj.options[:unique_by] = :uuid
89 | assert_equal :uuid, @obj.send(:unique_by)
90 | end
91 |
92 | def test_input_file
93 | assert_equal "#{@@test_dir}/data/customer.csv", @obj.send(:input_file)
94 |
95 | @obj.options.delete :input_file
96 | assert_raises (KeyError) { @obj.send(:input_file) }
97 | end
98 |
99 | def test_ignore_input_file_header
100 | @obj.options.delete :ignore_input_file_header
101 | assert_equal false, @obj.send(:ignore_input_file_header)
102 |
103 | @obj.options[:ignore_input_file_header] = true
104 | assert_equal true, @obj.send(:ignore_input_file_header)
105 | end
106 |
107 | def test_copy_to_target_table
108 | @obj.stub :copy_to_target_table_sql, 'select now()' do
109 | assert_instance_of PG::Result, @obj.send(:copy_to_target_table)
110 | end
111 | end
112 |
113 | def test_copy_to_staging_table
114 | @obj.stub :copy_to_staging_table_sql, 'select now()' do
115 | assert_instance_of PG::Result, @obj.send(:copy_to_staging_table)
116 | end
117 | end
118 |
119 | def test_copy_to_target_table_sql
120 | expected_sql = <<-SQL
121 | COPY customers (id, email, first_name, last_name)
122 | FROM '#{@@test_dir}/data/customer.csv'
123 | WITH
124 | DELIMITER ','
125 | NULL '\\N'
126 | CSV
127 | SQL
128 | sql = @obj.send(:copy_to_target_table_sql)
129 |
130 | assert_equal wrap_sql(expected_sql), wrap_sql(sql)
131 | end
132 |
133 | def test_copy_to_target_table_sql_when_ignore_input_file_header
134 | expected_sql = <<-SQL
135 | COPY customers (id, email, first_name, last_name)
136 | FROM '#{@@test_dir}/data/customer.csv'
137 | WITH
138 | HEADER
139 | DELIMITER ','
140 | NULL '\\N'
141 | CSV
142 | SQL
143 |
144 | @obj.stub :ignore_input_file_header, true do
145 | sql = @obj.send(:copy_to_target_table_sql)
146 |
147 | assert_equal wrap_sql(expected_sql), wrap_sql(sql)
148 | end
149 | end
150 |
151 | def test_copy_to_staging_table_sql
152 | expected_sql = <<-SQL
153 | COPY customers_staging (id, email, first_name, last_name)
154 | FROM '#{@@test_dir}/data/customer.csv'
155 | WITH
156 | DELIMITER ','
157 | NULL '\\N'
158 | CSV
159 | SQL
160 | sql = @obj.send(:copy_to_staging_table_sql)
161 |
162 | assert_equal wrap_sql(expected_sql), wrap_sql(sql)
163 | end
164 |
165 | def test_copy_to_staging_table_sql_when_ignore_input_file_header
166 | expected_sql = <<-SQL
167 | COPY customers_staging (id, email, first_name, last_name)
168 | FROM '#{@@test_dir}/data/customer.csv'
169 | WITH
170 | HEADER
171 | DELIMITER ','
172 | NULL '\\N'
173 | CSV
174 | SQL
175 |
176 | @obj.stub :ignore_input_file_header, true do
177 | sql = @obj.send(:copy_to_staging_table_sql)
178 |
179 | assert_equal wrap_sql(expected_sql), wrap_sql(sql)
180 | end
181 | end
182 |
183 | end
184 |
--------------------------------------------------------------------------------
/test/kiba/features/csv_to_x_test.rb:
--------------------------------------------------------------------------------
1 | require 'test_helper'
2 |
3 | class Kiba::Features::CsvToXTest < Minitest::Test
4 |
5 | attr_reader :src_csv_path, :src_csv_with_header_path
6 | attr_reader :dest_mysql2_db, :dest_mysql2_url, :dest_pg_db, :dest_pg_url
7 |
8 | def build
9 | @src_csv_path = make_csv_file
10 | @src_csv_with_header_path = make_csv_file
11 |
12 | @dest_mysql2_db = @@sequel_dbs[:mysql2_dest]
13 | @dest_mysql2_url = @@connect_urls[:mysql2_dest]
14 |
15 | @dest_pg_db = @@sequel_dbs[:pg_dest]
16 | @dest_pg_url = @@connect_urls[:pg_dest]
17 |
18 | # default mode is 0600
19 | FileUtils.chmod 0666, src_csv_path
20 | CSV.open(src_csv_path, "wb") do |csv|
21 | 1.upto(10).each do |n|
22 | csv << [n, "user#{n}@example.com", "first_name#{n}", "last_name#{n}"]
23 | end
24 | end
25 |
26 | # default mode is 0600
27 | FileUtils.chmod 0666, src_csv_with_header_path
28 | CSV.open(src_csv_with_header_path, "wb") do |csv|
29 | csv << [:id, :email, :first_name, :last_name]
30 | 1.upto(10).each do |n|
31 | csv << [n, "user#{n}@example.com", "first_name#{n}", "last_name#{n}"]
32 | end
33 | end
34 |
35 | dest_mysql2_db.create_table! :customers do
36 | primary_key :id
37 | column :email, String
38 | column :first_name, String
39 | column :last_name, String
40 | end
41 |
42 |
43 | if dest_pg_db.table_exists? :customers_staging
44 | dest_pg_db.drop_table :customers_staging
45 | end
46 | dest_pg_db.create_table! :customers do
47 | primary_key :id
48 | column :email, String
49 | column :first_name, String
50 | column :last_name, String
51 | end
52 | end
53 |
54 | def test_to_mysql_with_examples_customer_csv_to_mysql
55 | build
56 |
57 | etl_content = <<-ETL
58 | require 'kiba/plus'
59 |
60 | DEST_URL = '#{dest_mysql2_url}'
61 |
62 | destination Kiba::Plus::Destination::MysqlBulk, { :connect_url => DEST_URL,
63 | :table_name => "customers",
64 | :input_file => '#{src_csv_path}',
65 | :truncate => true,
66 | :columns => [:id, :email, :first_name, :last_name],
67 | :incremental => false
68 | }
69 |
70 | post_process do
71 | end
72 | ETL
73 | run_etl_content etl_content
74 |
75 | assert_equal 10, dest_mysql2_db[:customers].count
76 | assert_equal 'user10@example.com', dest_mysql2_db[:customers].order(:id).last[:email]
77 | end
78 |
79 | def test_to_mysql_with_csv_have_header
80 | build
81 |
82 | etl_content = <<-ETL
83 | require 'kiba/plus'
84 |
85 | DEST_URL = '#{dest_mysql2_url}'
86 |
87 | destination Kiba::Plus::Destination::MysqlBulk, { :connect_url => DEST_URL,
88 | :table_name => "customers",
89 | :input_file => '#{src_csv_with_header_path}',
90 | :truncate => true,
91 | :columns => [:id, :email, :first_name, :last_name],
92 | :incremental => false,
93 | :ignore_input_file_header => true
94 | }
95 |
96 | post_process do
97 | end
98 | ETL
99 | run_etl_content etl_content
100 |
101 | assert_equal 10, dest_mysql2_db[:customers].count
102 | assert_equal 'user10@example.com', dest_mysql2_db[:customers].order(:id).last[:email]
103 | end
104 |
105 | def test_to_pg_with_examples_customer_csv_to_pg
106 | build
107 |
108 | #
109 | # Because csv file should not in /tmp dir
110 | #
111 | pg_copy_tmp_dir = File.join(@@test_dir, 'pg_copy_tmp')
112 | src_csv_path_with_pg = File.join pg_copy_tmp_dir, File.basename(src_csv_path)
113 | FileUtils.cp src_csv_path, src_csv_path_with_pg
114 |
115 | etl_content = <<-ETL
116 | require 'kiba/plus'
117 |
118 | DEST_URL = '#{dest_pg_url}'
119 |
120 | destination Kiba::Plus::Destination::PgBulk, { :connect_url => DEST_URL,
121 | :table_name => "customers",
122 | :input_file => '#{src_csv_path_with_pg}',
123 | :truncate => true,
124 | :columns => [:id, :email, :first_name, :last_name],
125 | :incremental => false
126 | }
127 |
128 | post_process do
129 | end
130 | ETL
131 | run_etl_content etl_content
132 |
133 | FileUtils.rm_rf src_csv_path_with_pg
134 |
135 | assert_equal 10, dest_pg_db[:customers].count
136 | assert_equal 'user10@example.com', dest_pg_db[:customers].order(:id).last[:email]
137 | end
138 |
139 | def test_to_pg_with_csv_have_header
140 | build
141 |
142 | pg_copy_tmp_dir = File.join(@@test_dir, 'pg_copy_tmp')
143 | src_csv_path_with_pg = File.join pg_copy_tmp_dir, File.basename(src_csv_with_header_path)
144 | FileUtils.cp src_csv_with_header_path, src_csv_path_with_pg
145 |
146 | etl_content = <<-ETL
147 | require 'kiba/plus'
148 |
149 | DEST_URL = '#{dest_pg_url}'
150 |
151 | destination Kiba::Plus::Destination::PgBulk, { :connect_url => DEST_URL,
152 | :table_name => "customers",
153 | :input_file => '#{src_csv_path_with_pg}',
154 | :truncate => true,
155 | :columns => [:id, :email, :first_name, :last_name],
156 | :incremental => false,
157 | :ignore_input_file_header => true
158 | }
159 |
160 | post_process do
161 | end
162 | ETL
163 | run_etl_content etl_content
164 |
165 | FileUtils.rm_rf src_csv_path_with_pg
166 |
167 | assert_equal 10, dest_pg_db[:customers].count
168 | assert_equal 'user10@example.com', dest_pg_db[:customers].order(:id).last[:email]
169 | end
170 | end
171 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 | {one line to give the program's name and a brief idea of what it does.}
635 | Copyright (C) {year} {name of author}
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | {project} Copyright (C) {year} {fullname}
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------