dohmysql 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (46) hide show
  1. data/MIT-LICENSE +20 -0
  2. data/bin/makedb +28 -0
  3. data/lib/doh/mysql/abstract_row.rb +80 -0
  4. data/lib/doh/mysql/activate.rb +31 -0
  5. data/lib/doh/mysql/cache_connector.rb +54 -0
  6. data/lib/doh/mysql/connector_instance.rb +79 -0
  7. data/lib/doh/mysql/connector_util.rb +27 -0
  8. data/lib/doh/mysql/convert.rb +18 -0
  9. data/lib/doh/mysql/current_date.rb +22 -0
  10. data/lib/doh/mysql/database_creator.rb +101 -0
  11. data/lib/doh/mysql/db_date.rb +28 -0
  12. data/lib/doh/mysql/default_type_guesser.rb +37 -0
  13. data/lib/doh/mysql/error.rb +7 -0
  14. data/lib/doh/mysql/handle.rb +218 -0
  15. data/lib/doh/mysql/hash_row.rb +13 -0
  16. data/lib/doh/mysql/load_sql.rb +26 -0
  17. data/lib/doh/mysql/metadata_util.rb +73 -0
  18. data/lib/doh/mysql/parse.rb +36 -0
  19. data/lib/doh/mysql/raw_row_builder.rb +15 -0
  20. data/lib/doh/mysql/readonly_row.rb +26 -0
  21. data/lib/doh/mysql/require_dbtypes.rb +8 -0
  22. data/lib/doh/mysql/smart_row.rb +156 -0
  23. data/lib/doh/mysql/to_sql.rb +65 -0
  24. data/lib/doh/mysql/typed_row_builder.rb +28 -0
  25. data/lib/doh/mysql/types.rb +33 -0
  26. data/lib/doh/mysql/unquoted.rb +17 -0
  27. data/lib/doh/mysql/version.rb +102 -0
  28. data/lib/doh/mysql/virtual.rb +17 -0
  29. data/lib/doh/mysql/writable_row.rb +59 -0
  30. data/lib/doh/mysql.rb +7 -0
  31. data/test/cache_connector.dt.rb +41 -0
  32. data/test/connector.yml +4 -0
  33. data/test/connector.yml.tmpl +4 -0
  34. data/test/connector_instance.dt.rb +32 -0
  35. data/test/convert.dt.rb +45 -0
  36. data/test/db_unit_test.rb +10 -0
  37. data/test/handle.dt.rb +112 -0
  38. data/test/metadata_util.dt.rb +53 -0
  39. data/test/parse.dt.rb +39 -0
  40. data/test/readonly_row.dt.rb +85 -0
  41. data/test/smart_row.dt.rb +21 -0
  42. data/test/to_sql.dt.rb +19 -0
  43. data/test/types.dt.rb +32 -0
  44. data/test/unquoted.dt.rb +16 -0
  45. data/test/writable_row.dt.rb +21 -0
  46. metadata +118 -0
@@ -0,0 +1,17 @@
1
+ module DohDb
2
+
3
+ class Unquoted < String
4
+ def to_sql
5
+ to_s
6
+ end
7
+ end
8
+
9
+ def self.unquoted(str)
10
+ Unquoted.new(str)
11
+ end
12
+
13
+ NOW = Unquoted.new('NOW()').freeze
14
+ TODAY = Unquoted.new('CURDATE()').freeze
15
+ NULL = Unquoted.new('NULL').freeze
16
+
17
+ end
@@ -0,0 +1,102 @@
1
+ require 'doh/mysql/connector_instance'
2
+ require 'yaml'
3
+
4
+ module DohDb
5
+
6
+ def self.locked_filename(database)
7
+ File.join(Doh::root, 'database', database, 'migrate/locked.yml')
8
+ end
9
+
10
+ def self.migration_filename(database, version, upordown = 'up')
11
+ version_str = version.to_s.rjust(3, '0')
12
+ File.join(Doh::root, 'database', database, "migrate/#{version_str}_#{upordown}.sql")
13
+ end
14
+
15
+ def self.current_database_version(database = nil)
16
+ if database.nil?
17
+ table = 'version'
18
+ else
19
+ table = database + '.version'
20
+ end
21
+ DohDb::select_field("SELECT version FROM #{table}").to_i
22
+ end
23
+
24
+ def self.latest_database_version(database = nil)
25
+ locked_version = locked_database_version(database)
26
+ unlocked_version = locked_version + 1
27
+ unlocked_migration_file = migration_filename(database, unlocked_version)
28
+ if File.exist?(unlocked_migration_file)
29
+ unlocked_version
30
+ else
31
+ locked_version
32
+ end
33
+ end
34
+
35
+ def self.locked_version_info(database = nil)
36
+ database ||= (DohDb::connector_instance && DohDb::connector_instance.database) || Doh::config['primary_database']
37
+ filename = locked_filename(database)
38
+ return [0, nil] unless File.exist?(filename)
39
+ YAML.load_file(filename)
40
+ end
41
+
42
+ def self.locked_database_version(database = nil)
43
+ locked_version_info(database).first
44
+ end
45
+
46
+ def self.locked_svn_revision(database = nil)
47
+ locked_version_info(database).last
48
+ end
49
+
50
+ def self.update_locked_file(database)
51
+ locked_file = locked_filename(database)
52
+ if File.exist?(locked_file)
53
+ new_version = YAML.load_file(locked_file).first + 1
54
+ else
55
+ new_version = 0
56
+ need_to_add = true
57
+ end
58
+
59
+ file_to_check = ''
60
+ if need_to_add
61
+ file_to_check = File.join(Doh::root, "database")
62
+ else
63
+ unlocked_migration_file = migration_filename(database, new_version)
64
+ return [true, "nothing to lock"] unless File.exist?(unlocked_migration_file)
65
+
66
+ svnout = `svn st #{unlocked_migration_file}`
67
+ unless svnout.strip.empty?
68
+ return [false, "svn status shows local changes to #{unlocked_migration_file} -- this needs to be resolved before updating the migration locked file"]
69
+ end
70
+
71
+ file_to_check = unlocked_migration_file
72
+ end
73
+
74
+ `svn update #{file_to_check}`
75
+ svnout = `svn st -v #{file_to_check}`.split("\n")
76
+ svnout =~ /(\d+)/
77
+ revision = svnout.collect {|elem| elem =~ /(\d+)/; $1.to_i}.max
78
+ if !revision
79
+ return [false, "unable to extract svn revision from: '#{svnout}'"]
80
+ end
81
+
82
+ outfile = File.new(locked_file, 'w')
83
+ outfile.puts([new_version, revision.to_i].inspect)
84
+ outfile.close
85
+
86
+ if need_to_add
87
+ svnout = `svn add #{locked_file}`
88
+ if svnout[0,1] != 'A'
89
+ return [false, "failed to svn add #{locked_file}"]
90
+ end
91
+ end
92
+
93
+ msg = "migrate lock for #{database} database, version #{new_version}"
94
+ svnout = `svn ci -m \"#{msg}\" #{locked_file}`
95
+ unless svnout.index("Committed revision")
96
+ return [false, "failed to svn ci #{locked_file}"]
97
+ end
98
+
99
+ [true, "#{locked_file} successfully updated"]
100
+ end
101
+
102
+ end
@@ -0,0 +1,17 @@
1
+ require 'doh/mysql/metadata_util'
2
+ require 'doh/mysql/readonly_row'
3
+ require 'doh/mysql/types'
4
+
5
+ module DohDb
6
+
7
+ class LinkedRow
8
+ def self.build(field, idvalue)
9
+ return ReadOnlyRow.new([], []) if idvalue.to_i == 0
10
+ table = field.sub(/_id/, '')
11
+ table = table.rafter('_') unless DohDb::table_exist?(table)
12
+ raise "unable to determine child table name for field #{field}" unless DohDb::table_exist?(table)
13
+ DohDb::select_row("SELECT * FROM #{table} WHERE #{DohDb::find_primary_key(table)} = #{idvalue}", DohDb::find_row_type(table) || :smart)
14
+ end
15
+ end
16
+
17
+ end
@@ -0,0 +1,59 @@
1
+ require 'doh/core_ext/string'
2
+ require 'doh/mysql/abstract_row'
3
+ require 'set'
4
+
5
+ module DohDb
6
+
7
+ class WritableRow < AbstractRow
8
+ attr_reader :changed_keys
9
+
10
+ # can accept 2 arguments: keys array, values array
11
+ # or 1 argument: a hash
12
+ def initialize(*args)
13
+ keys, values = parse_initialize_args(*args)
14
+ @keys = keys.dup
15
+ @values = values.dup
16
+ @changed_keys = Set.new
17
+ end
18
+
19
+ def initialize_copy(orig)
20
+ super(orig)
21
+ @changed_keys = Set.new
22
+ end
23
+
24
+ def set(key, value)
25
+ index = @keys.index(key)
26
+ if index
27
+ @values[index] = value
28
+ else
29
+ @keys.push(key)
30
+ @values.push(value)
31
+ end
32
+ @changed_keys.add(key)
33
+ value
34
+ end
35
+ alias []= set
36
+
37
+ def clear_changed_keys
38
+ @changed_keys.clear
39
+ end
40
+
41
+ def method_missing(sym, *args)
42
+ name = sym.to_s
43
+ if name.lastn(1) == '='
44
+ key = name[0..-2]
45
+ assign = true
46
+ else
47
+ key = name
48
+ end
49
+ raise RuntimeError.new("unknown field: " + name) unless key?(key)
50
+
51
+ if assign
52
+ set(key, args.first)
53
+ else
54
+ get(key)
55
+ end
56
+ end
57
+ end
58
+
59
+ end
data/lib/doh/mysql.rb ADDED
@@ -0,0 +1,7 @@
1
+ require 'doh/mysql/cache_connector'
2
+ require 'doh/mysql/connector_instance'
3
+ require 'doh/mysql/handle'
4
+ require 'doh/mysql/to_sql'
5
+ require 'doh/mysql/db_date'
6
+ require 'doh/mysql/unquoted'
7
+ require 'doh/mysql/activate'
@@ -0,0 +1,41 @@
1
+ require_relative 'db_unit_test'
2
+
3
+ module DohDb
4
+
5
+ class Test_CacheConnector < DohTest::TestGroup
6
+ def create_table
7
+ @cc.request_handle.query("CREATE TEMPORARY TABLE #@tbl (id INT AUTO_INCREMENT KEY)")
8
+ end
9
+
10
+ def insert_record
11
+ @cc.request_handle.insert("INSERT INTO #@tbl (id) VALUES (null)")
12
+ end
13
+
14
+ def test_stuff
15
+ sharedcc = DohDb::connector_instance
16
+ @cc = DohDb::CacheConnector.new(sharedcc.host, sharedcc.username, sharedcc.password, sharedcc.database, sharedcc.row_builder)
17
+ @tbl = 'doh_mysql_cache_connector_stuff_test'
18
+
19
+ create_table
20
+ assert_equal(1, insert_record)
21
+
22
+ dbh = @cc.request_handle
23
+ assert_equal(2, insert_record)
24
+ dbh.close
25
+ # temporary table gets deleted on handle close
26
+ create_table
27
+
28
+ #test it resets the handle
29
+ @cc.reset
30
+ create_table
31
+ @cc.reset
32
+ @cc.reset
33
+
34
+ # test it still works after timeout
35
+ create_table
36
+ @cc.timeout = -1
37
+ create_table
38
+ end
39
+ end
40
+
41
+ end
@@ -0,0 +1,4 @@
1
+ host: localhost
2
+ database: test
3
+ username: root
4
+ password:
@@ -0,0 +1,4 @@
1
+ host: localhost
2
+ database: test
3
+ username: doh_mysql
4
+ password:
@@ -0,0 +1,32 @@
1
+ require_relative 'db_unit_test'
2
+
3
+ module DohDb
4
+
5
+ class Test_ConnectorInstance < DohTest::TestGroup
6
+ def test_stuff
7
+ tbl = "doh_mysql_connector_instance_stuff_test"
8
+ DohDb::query("CREATE TEMPORARY TABLE #{tbl} (id INT UNSIGNED AUTO_INCREMENT NOT NULL KEY, value INT NOT NULL DEFAULT 0, created_on DATE, created_at DATETIME, money DECIMAL(7,2) NOT NULL DEFAULT 0)")
9
+ assert_equal(1, DohDb::insert("INSERT INTO #{tbl} (id, created_on, created_at, money) VALUES (null, CURDATE(), '2007-01-01 10:30:05', 10.5)"))
10
+ assert_equal(2, DohDb::insert("INSERT INTO #{tbl} (id, created_on) VALUES (null, 0)"))
11
+ assert_equal(1, DohDb::update("UPDATE #{tbl} SET money = 10.8 WHERE id = 1"))
12
+ assert_equal(BigDecimal('10.80'), DohDb::select_field("SELECT money FROM #{tbl} WHERE id = 1"))
13
+ assert_raises(UnexpectedQueryResult) {DohDb::select_row("SELECT * FROM #{tbl} WHERE id = 7")}
14
+ assert_equal(nil, DohDb::select_optional_row("SELECT * FROM #{tbl} WHERE id = 7"))
15
+ assert_raises(UnexpectedQueryResult){DohDb::select_optional_row("SELECT * FROM #{tbl} WHERE id < 3")}
16
+ assert_equal(nil, DohDb::select_optional_field("SELECT money FROM #{tbl} WHERE id = 7"))
17
+ assert_raises(UnexpectedQueryResult) {DohDb::select_field("SELECT money FROM #{tbl} WHERE id = 7")}
18
+ assert_equal(1, DohDb::update_row("UPDATE #{tbl} SET money = 10.95 WHERE id = 1"))
19
+ assert_raises(Mysql::Error){DohDb::query("some invalid sql here")}
20
+ # TODO: re-enable
21
+ # assert(DohTest::pop_error)
22
+ assert_raises(UnexpectedQueryResult) {DohDb::update_row("UPDATE #{tbl} SET money = 10.95 WHERE id = 7")}
23
+ onerow = DohDb::select_row("SELECT * FROM #{tbl} WHERE id = 1")
24
+ assert_equal(1, onerow['id'])
25
+ onerow = DohDb::select_optional_row("SELECT * FROM #{tbl} WHERE id = 1")
26
+ assert_equal(1, onerow['id'])
27
+ rows = DohDb::select("SELECT * FROM #{tbl}")
28
+ rows.each {|row| assert(row['id'] != 0)}
29
+ end
30
+ end
31
+
32
+ end
@@ -0,0 +1,45 @@
1
+ require_relative 'db_unit_test'
2
+ require 'doh/mysql/convert'
3
+
4
+ module DohDb
5
+
6
+ class Test_Convert < DohTest::TestGroup
7
+ def before_each
8
+ @tbl = "doh_mysql_convert_tests"
9
+ DohDb::query("DROP TABLE IF EXISTS #@tbl")
10
+ DohDb::request_handle.query("CREATE TABLE #{@tbl} (not_null_field CHAR(1) NOT NULL, null_ok_field CHAR(1), int_field INT, bool_field TINYINT(1), date_field DATE, datetime_field DATETIME)")
11
+ end
12
+
13
+ def after_each
14
+ DohDb::query("DROP TABLE IF EXISTS #@tbl")
15
+ end
16
+
17
+ def convert(value)
18
+ DohDb::convert(@tbl, @field, value)
19
+ end
20
+
21
+ def verify(converted, original)
22
+ assert_equal(converted, convert(original))
23
+ end
24
+
25
+ def verify_same(value)
26
+ verify(value, value)
27
+ end
28
+
29
+ def verify_exception(value, exception_class)
30
+ assert_raises(exception_class) { convert(value) }
31
+ end
32
+
33
+ def test_nil_null
34
+ # assert_raises(UnknownColumn) { DohDb::convert('some_table_that_doesnt_exist', 'some_column_that_doesnt_exist', 'blah') }
35
+ assert_equal('blah', DohDb::convert('some_table_that_doesnt_exist', 'some_column_that_doesnt_exist', 'blah'))
36
+ assert_equal('blah', DohDb::convert('', 'some_column_that_doesnt_exist', 'blah'))
37
+ assert_raises(CannotBeNull) { DohDb::convert(@tbl, 'not_null_field', nil) }
38
+ assert_equal(nil, DohDb::convert(@tbl, 'null_ok_field', nil))
39
+ assert_equal('', DohDb::convert(@tbl, 'not_null_field', ''))
40
+ assert_equal(nil, DohDb::convert(@tbl, 'null_ok_field', ''))
41
+ assert_equal(nil, DohDb::convert(@tbl, 'int_field', ''))
42
+ end
43
+ end
44
+
45
+ end
@@ -0,0 +1,10 @@
1
+ require 'doh/mysql/connector_instance'
2
+ require 'doh/mysql/cache_connector'
3
+ require 'yaml'
4
+
5
+ config_filename = File.join(File.dirname(__FILE__), 'connector.yml')
6
+ raise RuntimeError.new("mysql connector configuration file (#{config_filename}) must exist (see #{config_filename}.tmpl for an example)") unless File.exist?(config_filename)
7
+ config = YAML.load_file(config_filename)
8
+
9
+ connector = DohDb::CacheConnector.new(config['host'], config['username'], config['password'], config['database'])
10
+ DohDb::set_connector_instance(connector)
data/test/handle.dt.rb ADDED
@@ -0,0 +1,112 @@
1
+ require_relative 'db_unit_test'
2
+ require 'doh/core_ext/hash'
3
+
4
+ module DohDb
5
+
6
+ class Test_Handle < DohTest::TestGroup
7
+ def test_stuff
8
+ dbh = DohDb::request_handle
9
+ tbl = "doh_mysql_handle_stuff_test"
10
+ dbh.query("CREATE TEMPORARY TABLE #{tbl} (id INT UNSIGNED AUTO_INCREMENT NOT NULL KEY, value INT NOT NULL DEFAULT 0, created_on DATE, created_at DATETIME, money DECIMAL(7,2) NOT NULL DEFAULT 0)")
11
+ assert_equal(1, dbh.insert("INSERT INTO #{tbl} (id, created_on, created_at, money) VALUES (null, CURDATE(), '2007-01-01 10:30:05', 10.5)"))
12
+ assert_equal(2, dbh.insert("INSERT INTO #{tbl} (id, created_on, created_at) VALUES (null, 0, 0)"))
13
+ assert_equal(3, dbh.insert("INSERT INTO #{tbl} (id) VALUES (null)"))
14
+ onerow = dbh.select_row("SELECT * FROM #{tbl} WHERE id = 1")
15
+ assert_equal(1, onerow['id'])
16
+ rows = dbh.select("SELECT * FROM #{tbl}")
17
+ rows.each {|row| assert(row['id'] != 0)}
18
+ end
19
+
20
+ def test_select_transpose_2fields
21
+ dbh = DohDb::request_handle
22
+ tbl = "doh_mysql_handle_select_transpose_2fields_test"
23
+ DohDb::query("CREATE TEMPORARY TABLE #{tbl} (field CHAR(30) NOT NULL, value CHAR(30) NOT NULL)")
24
+ DohDb::query("INSERT INTO #{tbl} SET field = 'some_name', value = 'some_value'")
25
+ DohDb::query("INSERT INTO #{tbl} SET field = 'other_name', value = 'matching_other_value'")
26
+ DohDb::query("INSERT INTO #{tbl} SET field = 'yet_another_name', value = 'strange_value'")
27
+ hash = DohDb::select_transpose("SELECT field, value FROM #{tbl}")
28
+ assert_equal('some_value', hash['some_name'])
29
+ assert_equal('matching_other_value', hash['other_name'])
30
+ assert_equal('strange_value', hash['yet_another_name'])
31
+ end
32
+
33
+ def test_select_transpose_3fields
34
+ dbh = DohDb::request_handle
35
+ tbl = "doh_mysql_handle_select_transpose_3fields_test"
36
+ DohDb::query("CREATE TEMPORARY TABLE #{tbl} (field CHAR(30), some_value CHAR(30), other_value CHAR(30))")
37
+ DohDb::query("INSERT INTO #{tbl} SET field = 'some_name', some_value = 'some_value', other_value = 'blah'")
38
+ DohDb::query("INSERT INTO #{tbl} SET field = 'other_name', some_value = 'matching_other_value', other_value = 'blee'")
39
+ DohDb::query("INSERT INTO #{tbl} SET field = 'yet_another_name', some_value = 'strange_value', other_value = 'bloo'")
40
+ hash = DohDb::select_transpose("SELECT field, some_value, other_value FROM #{tbl}")
41
+ assert_equal(hash['some_name'], {'some_value' => 'some_value', 'other_value' => 'blah'})
42
+ assert_equal(hash['other_name'], {'some_value' => 'matching_other_value', 'other_value' => 'blee'})
43
+ assert_equal(hash['yet_another_name'], {'some_value' => 'strange_value', 'other_value' => 'bloo'})
44
+ end
45
+
46
+ def test_select_values
47
+ dbh = DohDb::request_handle
48
+ tbl = "doh_mysql_handle_select_values_test"
49
+ DohDb::query("CREATE TEMPORARY TABLE #{tbl} (field CHAR(30), some_value CHAR(30))")
50
+ DohDb::query("INSERT INTO #{tbl} SET field = 'some_name', some_value = 'some_value'")
51
+ assert_equal([['some_name', 'some_value']], DohDb::select_values("SELECT field, some_value FROM #{tbl}"))
52
+ assert_equal([['some_name']], DohDb::select_values("SELECT field FROM #{tbl}"))
53
+ end
54
+
55
+ def test_multi_select
56
+ dbh = DohDb::request_handle
57
+ tbl = "doh_mysql_handle_multi_select_test"
58
+ DohDb::query("CREATE TEMPORARY TABLE #{tbl} (value CHAR(30))")
59
+ DohDb::query("INSERT INTO #{tbl} SET value = 'first'")
60
+ DohDb::query("INSERT INTO #{tbl} SET value = 'second'")
61
+
62
+ stmts = []
63
+ stmts.push("SELECT * FROM #{tbl}")
64
+ stmts.push("INSERT INTO #{tbl} SET value = 'third'")
65
+ stmts.push(["SELECT * FROM #{tbl}", :hash])
66
+ stmts.push("SELECT * FROM #{tbl}")
67
+ stmts.push("INSERT INTO #{tbl} SET value = 'fourth'")
68
+ stmts.push(["SELECT * FROM #{tbl}", :smart])
69
+ select_results = DohDb::multi_select(stmts)
70
+ assert_equal(4, select_results.size)
71
+ assert_equal(4, DohDb::select_field("SELECT COUNT(*) FROM #{tbl}"))
72
+
73
+ curr_select = select_results[0]
74
+ assert_equal(2, curr_select.size)
75
+ assert_instance_of(ReadOnlyRow, curr_select[0])
76
+ assert_equal({'value' => 'first'}, curr_select[0].to_h)
77
+ assert_equal({'value' => 'second'}, curr_select[1].to_h)
78
+
79
+ curr_select = select_results[1]
80
+ assert_equal(3, curr_select.size)
81
+ assert_instance_of(Hash, curr_select[0])
82
+ assert_equal({'value' => 'first'}, curr_select[0].to_h)
83
+ assert_equal({'value' => 'second'}, curr_select[1].to_h)
84
+ assert_equal({'value' => 'third'}, curr_select[2].to_h)
85
+
86
+ curr_select = select_results[2]
87
+ assert_equal(3, curr_select.size)
88
+ assert_equal({'value' => 'first'}, curr_select[0].to_h)
89
+ assert_equal({'value' => 'second'}, curr_select[1].to_h)
90
+ assert_equal({'value' => 'third'}, curr_select[2].to_h)
91
+
92
+ curr_select = select_results[3]
93
+ assert_equal(4, curr_select.size)
94
+ assert_instance_of(SmartRow, curr_select[0])
95
+ assert_equal({'value' => 'first'}, curr_select[0].to_h)
96
+ assert_equal({'value' => 'second'}, curr_select[1].to_h)
97
+ assert_equal({'value' => 'third'}, curr_select[2].to_h)
98
+ assert_equal({'value' => 'fourth'}, curr_select[3].to_h)
99
+ end
100
+
101
+ def test_insert_hash
102
+ dbh = DohDb::request_handle
103
+ tbl = "doh_mysql_insert_hash_test"
104
+ dbh.query("CREATE TEMPORARY TABLE #{tbl} (value INT KEY)")
105
+ hash1 = {'value' => 1}
106
+ assert_equal(0, dbh.insert_hash(hash1, tbl))
107
+ assert_raises(Mysql::Error) { dbh.insert_hash(hash1, tbl) }
108
+ assert_equal(0, dbh.insert_hash(hash1, tbl, true))
109
+ end
110
+ end
111
+
112
+ end
@@ -0,0 +1,53 @@
1
+ require_relative 'db_unit_test'
2
+ require 'doh/mysql/metadata_util'
3
+
4
+ module DohDb
5
+
6
+ class Test_metadata_util < DohTest::TestGroup
7
+ def tbl
8
+ "doh_mysql_metadata_util_test"
9
+ end
10
+
11
+ def test_stuff
12
+ dbh = DohDb::request_handle
13
+ dbh.query("CREATE TABLE #{tbl} (num INT, str CHAR(7))")
14
+ column_info = DohDb::column_info(tbl)
15
+ info = column_info['str']
16
+ assert_equal('char', info['data_type'])
17
+ assert_equal(7, info['character_maximum_length'])
18
+ info = column_info['num']
19
+ assert_equal('int', info['data_type'])
20
+ assert_equal(nil, info['character_maximum_length'])
21
+
22
+ assert_equal(7, DohDb::field_character_size(tbl, 'str'))
23
+ assert_equal(nil, DohDb::field_character_size(tbl, 'num'))
24
+
25
+ row = {'num' => 'blahblahblah', 'str' => 'blahblahblah'}
26
+ DohDb::chop_character_fields!(tbl, row)
27
+ assert_equal('blahblahblah', row['num'])
28
+ assert_equal('blahbla', row['str'])
29
+
30
+ row = {'num' => 'blahblahblah', 'str' => 'blahblahblah'}
31
+ newrow = DohDb::chop_character_fields(tbl, row)
32
+ assert_equal('blahblahblah', newrow['num'])
33
+ assert_equal('blahbla', newrow['str'])
34
+ assert_equal('blahblahblah', row['num'])
35
+ assert_equal('blahblahblah', row['str'])
36
+
37
+ assert(DohDb::table_exist?(tbl))
38
+
39
+ assert_equal('num', DohDb::find_primary_key(tbl))
40
+ assert_raises(RuntimeError) { DohDb::find_primary_key(tbl, "this_database_doesnt_exist") }
41
+ assert_raises(RuntimeError) { DohDb::find_primary_key("this table doesn't exist") }
42
+ end
43
+
44
+ def before_each
45
+ DohDb::query("DROP TABLE IF EXISTS #{tbl}")
46
+ end
47
+
48
+ def after_each
49
+ DohDb::query("DROP TABLE IF EXISTS #{tbl}")
50
+ end
51
+ end
52
+
53
+ end
data/test/parse.dt.rb ADDED
@@ -0,0 +1,39 @@
1
+ require 'doh/mysql/parse'
2
+
3
+ module DohDb
4
+
5
+ class Test_Parse < DohTest::TestGroup
6
+ def test_bool
7
+ assert_equal(false, DohDb::parse_bool('0'))
8
+ assert_equal(true, DohDb::parse_bool('1'))
9
+ assert_raises(ArgumentError) {DohDb::parse_bool('blah')}
10
+ end
11
+
12
+ def test_date
13
+ assert_raises(ArgumentError) {DohDb::parse_date('blah')}
14
+ assert_equal(Date.new(2008,2,14), DohDb::parse_date('2008-02-14'))
15
+ assert_raises(ArgumentError) {DohDb::parse_date('20080214')}
16
+ assert_not_equal(Date.new(2008,2,14), DohDb::parse_date('2008-02-15'))
17
+ assert_equal(nil, DohDb::parse_date('0000-00-00'))
18
+ end
19
+
20
+ def test_datetime
21
+ assert_raises(ArgumentError) {DohDb::parse_date('blah')}
22
+ assert_raises(ArgumentError) {DohDb::parse_datetime('zzzzzzzzzzzzzzzzzzz')}
23
+ assert_equal(DateTime.new(2008,2,14,10,20,30), DohDb::parse_datetime('2008-02-14 10:20:30'))
24
+ assert_not_equal(DateTime.new(2008,2,14,10,20,30), DohDb::parse_datetime('2008-02-14 10:20:31'))
25
+ assert_equal(nil, DohDb::parse_datetime('0000-00-00 00:00:00'))
26
+ end
27
+
28
+ def test_decimal
29
+ assert_equal(BigDecimal.new('3.14'), DohDb::parse_decimal('3.14'))
30
+ assert_equal(BigDecimal.new('0.0'), DohDb::parse_decimal('sjdkflsdjl'))
31
+ end
32
+
33
+ def test_int
34
+ assert_equal(3, DohDb::parse_int('3'))
35
+ assert_equal(0, DohDb::parse_int('sjdkflsdjl'))
36
+ end
37
+ end
38
+
39
+ end
@@ -0,0 +1,85 @@
1
+ require 'doh/mysql/readonly_row'
2
+
3
+ module DohDb
4
+
5
+ class Test_ReadOnlyRow < DohTest::TestGroup
6
+ def before_each
7
+ @row = ReadOnlyRow.new(['id', 'fname', 'lname', 'other', 'flag', 'emptystr'], [3, 'george', 'bob', nil, true, ''])
8
+ end
9
+
10
+ def test_keys
11
+ assert_equal(['id', 'fname', 'lname', 'other', 'flag', 'emptystr'], @row.keys)
12
+ end
13
+
14
+ def test_at_bad
15
+ assert_raises(TypeError) {@row.at(nil)}
16
+ assert_raises(TypeError) {@row.at('id')}
17
+ assert_equal(nil, @row.at(8))
18
+ assert_equal(nil, @row.at(-10))
19
+ end
20
+
21
+ def test_bracket_get_bad
22
+ assert_equal(nil, @row[nil])
23
+ assert_equal(nil, @row['blee'])
24
+ assert_equal(nil, @row[8])
25
+ assert_equal(nil, @row[-10])
26
+ end
27
+
28
+ def test_bracket_get_valid
29
+ assert_equal(3, @row['id'])
30
+ assert_equal('george', @row['fname'])
31
+ assert_equal('bob', @row['lname'])
32
+ assert_equal(nil, @row['other'])
33
+ end
34
+
35
+ def test_key_exists_bad
36
+ assert_equal(false, @row.key?(nil))
37
+ assert_equal(false, @row.key?('blee'))
38
+ assert_equal(false, @row.key?(8))
39
+ assert_equal(false, @row.key?(-10))
40
+ assert_equal(false, @row.key?(-10))
41
+ end
42
+
43
+ def test_key_exists_valid
44
+ assert_equal(true, @row.key?('id'))
45
+ assert_equal(true, @row.key?('fname'))
46
+ assert_equal(true, @row.key?('lname'))
47
+ assert_equal(true, @row.key?('other'))
48
+ end
49
+
50
+ def test_to_a
51
+ ary = @row.to_a
52
+ assert_equal(6, ary.size)
53
+ assert_equal(['id', 3], ary.at(0))
54
+ assert_equal(['fname','george'], ary.at(1))
55
+ assert_equal(['lname', 'bob'], ary.at(2))
56
+ assert_equal(['other', nil], ary.at(3))
57
+ assert_equal(['flag', true], ary.at(4))
58
+ assert_equal(['emptystr', ''], ary.at(5))
59
+ end
60
+
61
+ def test_to_h
62
+ hsh = @row.to_h
63
+ assert_equal(6, hsh.size)
64
+ assert_equal(3, hsh['id'])
65
+ assert_equal('george', hsh['fname'])
66
+ assert_equal('bob', hsh['lname'])
67
+ assert_equal(nil, hsh['other'])
68
+ end
69
+
70
+ def test_method_missing
71
+ assert_equal('george', @row.fname)
72
+ assert_equal('bob', @row.lname)
73
+ assert_equal(nil, @row.other)
74
+ assert_raises(RuntimeError) {@row.this_field_doesnt_exist}
75
+ end
76
+
77
+ def test_empty_field
78
+ assert(!@row.empty_field?('id'))
79
+ assert(@row.empty_field?('other'))
80
+ assert(@row.empty_field?('emptystr'))
81
+ assert(@row.empty_field?('unknown_field_name'))
82
+ end
83
+ end
84
+
85
+ end
@@ -0,0 +1,21 @@
1
+ require 'doh/mysql/smart_row'
2
+
3
+ module DohDb
4
+
5
+ class Test_SmartRow < DohTest::TestGroup
6
+ def test_display
7
+ row = SmartRow.new(['flag'], [true])
8
+ assert_equal('', row.display('this_field_doesnt_exist'))
9
+ assert_raises(RuntimeError) { row.display.this_field_doesnt_exist }
10
+ assert_equal('yes', row.display('flag'))
11
+ assert_equal('yes', row.display.flag)
12
+ row2 = row.dup
13
+ assert_equal(true, row2.flag)
14
+ row2.flag = false
15
+ assert_equal(false, row2.flag)
16
+ assert_equal(true, row.flag)
17
+ assert_raises(RuntimeError) { row.this_field_doesnt_exist }
18
+ end
19
+ end
20
+
21
+ end