Browse Source

[master] Unit tests now use production database scripts

    Merges in trac4239.
Thomas Markwalder 9 years ago
parent
commit
131fcf52f2
36 changed files with 505 additions and 781 deletions
  1. 10 8
      configure.ac
  2. 1 1
      src/Makefile.am
  3. 1 1
      src/bin/admin/Makefile.am
  4. 14 33
      src/bin/admin/tests/mysql_tests.sh.in
  5. 15 27
      src/bin/admin/tests/pgsql_tests.sh.in
  6. 50 11
      src/lib/dhcpsrv/pgsql_lease_mgr.cc
  7. 0 1
      src/lib/dhcpsrv/tests/Makefile.am
  8. 5 5
      src/lib/dhcpsrv/tests/generic_lease_mgr_unittest.cc
  9. 5 5
      src/lib/dhcpsrv/tests/mysql_host_data_source_unittest.cc
  10. 8 8
      src/lib/dhcpsrv/tests/mysql_lease_mgr_unittest.cc
  11. 18 127
      src/lib/dhcpsrv/tests/pgsql_lease_mgr_unittest.cc
  12. 0 129
      src/lib/dhcpsrv/tests/schema_pgsql_copy.h
  13. 22 2
      src/lib/dhcpsrv/testutils/Makefile.am
  14. 27 90
      src/lib/dhcpsrv/testutils/mysql_schema.cc
  15. 39 32
      src/lib/dhcpsrv/testutils/mysql_schema.h
  16. 64 0
      src/lib/dhcpsrv/testutils/pgsql_schema.cc
  17. 68 0
      src/lib/dhcpsrv/testutils/pgsql_schema.h
  18. 73 0
      src/lib/dhcpsrv/testutils/schema.cc
  19. 41 0
      src/lib/dhcpsrv/testutils/schema.h
  20. 0 301
      src/lib/dhcpsrv/testutils/schema_mysql_copy.h
  21. 1 0
      src/share/Makefile.am
  22. 1 0
      src/share/database/Makefile.am
  23. 0 0
      src/share/database/scripts/Makefile.am
  24. 0 0
      src/share/database/scripts/mysql/.gitignore
  25. 1 0
      src/bin/admin/scripts/mysql/Makefile.am
  26. 0 0
      src/share/database/scripts/mysql/dhcpdb_create.mysql
  27. 24 0
      src/share/database/scripts/mysql/dhcpdb_drop.mysql
  28. 0 0
      src/share/database/scripts/mysql/upgrade_1.0_to_2.0.sh.in
  29. 0 0
      src/share/database/scripts/mysql/upgrade_2.0_to_3.0.sh.in
  30. 0 0
      src/share/database/scripts/mysql/upgrade_3.0_to_4.0.sh.in
  31. 0 0
      src/share/database/scripts/mysql/upgrade_4.0_to_4.1.sh.in
  32. 0 0
      src/share/database/scripts/pgsql/.gitignore
  33. 1 0
      src/bin/admin/scripts/pgsql/Makefile.am
  34. 1 0
      src/bin/admin/scripts/pgsql/dhcpdb_create.pgsql
  35. 15 0
      src/share/database/scripts/pgsql/dhcpdb_drop.pgsql
  36. 0 0
      src/share/database/scripts/pgsql/upgrade_1.0_to_2.0.sh.in

+ 10 - 8
configure.ac

@@ -1404,19 +1404,11 @@ AC_CONFIG_FILES([compatcheck/Makefile
                  src/bin/perfdhcp/tests/testdata/Makefile
                  src/bin/admin/Makefile
                  src/bin/admin/kea-admin
-                 src/bin/admin/scripts/Makefile
                  src/bin/admin/tests/Makefile
                  src/bin/admin/tests/data/Makefile
                  src/bin/admin/tests/memfile_tests.sh
                  src/bin/admin/tests/mysql_tests.sh
                  src/bin/admin/tests/pgsql_tests.sh
-                 src/bin/admin/scripts/mysql/Makefile
-                 src/bin/admin/scripts/mysql/upgrade_1.0_to_2.0.sh
-                 src/bin/admin/scripts/mysql/upgrade_2.0_to_3.0.sh
-                 src/bin/admin/scripts/mysql/upgrade_3.0_to_4.0.sh
-                 src/bin/admin/scripts/mysql/upgrade_4.0_to_4.1.sh
-                 src/bin/admin/scripts/pgsql/Makefile
-                 src/bin/admin/scripts/pgsql/upgrade_1.0_to_2.0.sh
                  src/hooks/Makefile
                  src/hooks/dhcp/Makefile
                  src/hooks/dhcp/user_chk/Makefile
@@ -1483,6 +1475,16 @@ AC_CONFIG_FILES([compatcheck/Makefile
                  src/lib/util/unittests/Makefile
                  src/lib/eval/Makefile
                  src/lib/eval/tests/Makefile
+                 src/share/Makefile
+                 src/share/database/Makefile
+                 src/share/database/scripts/Makefile
+                 src/share/database/scripts/mysql/Makefile
+                 src/share/database/scripts/mysql/upgrade_1.0_to_2.0.sh
+                 src/share/database/scripts/mysql/upgrade_2.0_to_3.0.sh
+                 src/share/database/scripts/mysql/upgrade_3.0_to_4.0.sh
+                 src/share/database/scripts/mysql/upgrade_4.0_to_4.1.sh
+                 src/share/database/scripts/pgsql/Makefile
+                 src/share/database/scripts/pgsql/upgrade_1.0_to_2.0.sh
                  tools/Makefile
                  tools/path_replacer.sh
 ])

+ 1 - 1
src/Makefile.am

@@ -1,4 +1,4 @@
-SUBDIRS = lib bin hooks
+SUBDIRS = share lib bin hooks
 
 EXTRA_DIST = \
 	cppcheck-suppress.lst		\

+ 1 - 1
src/bin/admin/Makefile.am

@@ -1,4 +1,4 @@
-SUBDIRS = . scripts tests
+SUBDIRS = . tests
 
 # Install kea-admin in sbin.
 sbin_SCRIPTS  = kea-admin

+ 14 - 33
src/bin/admin/tests/mysql_tests.sh.in

@@ -9,15 +9,11 @@
 # Include common test library.
 . @abs_top_builddir@/src/lib/testutils/dhcp_test_lib.sh
 
-# If the code is installed, include admin-utils.sh from the destination
-# directory. If not, include it from the sources.
-prefix=@prefix@
+# Include admin utilities
+. @abs_top_srcdir@/src/bin/admin/admin-utils.sh
 
-if [ -e @datarootdir@/@PACKAGE_NAME@/scripts/admin-utils.sh ]; then
-    . @datarootdir@/@PACKAGE_NAME@/scripts/admin-utils.sh
-else
-    . @abs_top_srcdir@/src/bin/admin/admin-utils.sh
-fi
+# Set path to the production schema scripts
+db_scripts_dir=@abs_top_srcdir@/src/share/database/scripts
 
 db_user="keatest"
 db_password="keatest"
@@ -30,24 +26,9 @@ keaadmin=@abs_top_builddir@/src/bin/admin/kea-admin
 mysql_wipe() {
     printf "Wiping whole database %s\n" $db_name
 
-    # First we build the list of drop table commands
-    # We don't bother with "cascade" because as of MySQL
-    # 5.1 it is only there to ease porting, it doesn't
-    # actually do anything.
-    qry="\
-SELECT CONCAT('DROP TABLE ', table_schema, '.', table_name, ';') \
-FROM information_schema.tables \
-WHERE table_schema = 'keatest';"
-
-    drop_sql=`mysql_execute "${qry}"`
+    mysql -u$db_user -p$db_password $db_name >/dev/null 2>&1 < $db_scripts_dir/mysql/dhcpdb_drop.mysql
     ERRCODE=$?
-    assert_eq 0 $ERRCODE "mysql-wipe: table query failed, exit code %d, expected %d"
 
-    # We need to turn off referrential integrity checks so tables
-    # are dropped regardless of whether they are used in foreign keys.
-    # (This is what cascade would normally do)
-    mysql_execute "SET SESSION FOREIGN_KEY_CHECKS = 0;$drop_sql"
-    ERRCODE=$?
     assert_eq 0 $ERRCODE "mysql-wipe: drop table sql failed, exit code %d, expected %d"
 }
 
@@ -58,7 +39,7 @@ mysql_lease_init_test() {
     mysql_wipe
 
     # Ok, now let's initalize the database
-    ${keaadmin} lease-init mysql -u $db_user -p $db_password -n $db_name -d @abs_top_srcdir@/src/bin/admin/scripts
+    ${keaadmin} lease-init mysql -u $db_user -p $db_password -n $db_name -d $db_scripts_dir
     ERRCODE=$?
 
     assert_eq 0 $ERRCODE "kea-admin lease-init mysql returned non-zero status code %d, expected %d"
@@ -137,7 +118,7 @@ mysql_host_reservation_init_test() {
     mysql_wipe
 
     # Ok, now let's initalize the database
-    ${keaadmin} lease-init mysql -u $db_user -p $db_password -n $db_name -d @abs_top_srcdir@/src/bin/admin/scripts
+    ${keaadmin} lease-init mysql -u $db_user -p $db_password -n $db_name -d $db_scripts_dir
     ERRCODE=$?
 
     assert_eq 0 $ERRCODE "kea-admin lease-init mysql returned non-zero status code %d, expected %d"
@@ -202,12 +183,12 @@ mysql_upgrade_test() {
     mysql -u$db_user -p$db_password $db_name < @abs_top_srcdir@/src/bin/admin/tests/dhcpdb_create_1.0.mysql
 
     # Sanity check - verify that it reports version 1.0.
-    version=$(${keaadmin} lease-version mysql -u $db_user -p $db_password -n $db_name -d @abs_top_srcdir@/src/bin/admin/scripts)
+    version=$(${keaadmin} lease-version mysql -u $db_user -p $db_password -n $db_name -d $db_scripts_dir) 
 
     assert_str_eq "1.0" ${version} "Expected kea-admin to return %s, returned value was %s"
 
     # Ok, we have a 1.0 database. Let's upgrade it to 4.1
-    ${keaadmin} lease-upgrade mysql -u $db_user -p $db_password -n $db_name -d @abs_top_srcdir@/src/bin/admin/scripts
+    ${keaadmin} lease-upgrade mysql -u $db_user -p $db_password -n $db_name -d $db_scripts_dir 
     ERRCODE=$?
 
     assert_eq 0 $ERRCODE "kea-admin lease-upgrade mysql returned non-zero status code %d, expected %d"
@@ -309,7 +290,7 @@ EOF
     assert_eq 1 $count "lease6DumpData doesn't have order by clause. (returned count %d, expected %d)"
 
     # Verify upgraded schemd reports version 4.1.
-    version=$(${keaadmin} lease-version mysql -u $db_user -p $db_password -n $db_name -d @abs_top_srcdir@/src/bin/admin/scripts)
+    version=$(${keaadmin} lease-version mysql -u $db_user -p $db_password -n $db_name -d $db_scripts_dir) 
     assert_str_eq "4.1" ${version} "Expected kea-admin to return %s, returned value was %s"
 
 
@@ -346,7 +327,7 @@ mysql_lease4_dump_test() {
     mysql_wipe
 
     # Ok, now let's initalize the database
-    ${keaadmin} lease-init mysql -u $db_user -p $db_password -n $db_name -d $script_dir
+    ${keaadmin} lease-init mysql -u $db_user -p $db_password -n $db_name -d $db_scripts_dir
     ERRCODE=$?
     assert_eq 0 $ERRCODE "could not create database, expected exit code %d, actual %d"
 
@@ -361,7 +342,7 @@ insert into lease4 values(12,22,NULL,40,\"2015-03-03 11:01:07\",50,1,1,\"three.e
     assert_eq 0 $ERRCODE "insert into lease4 failed, expected exit code %d, actual %d"
 
     # Dump lease4 to output_file
-    ${keaadmin} lease-dump mysql -4 -u $db_user -p $db_password -n $db_name -d $script_dir -o $output_file
+    ${keaadmin} lease-dump mysql -4 -u $db_user -p $db_password -n $db_name -d $db_scripts_dir -o $output_file
     ERRCODE=$?
     assert_eq 0 $ERRCODE "kea-admin lease-dump -4 failed, expected exit code %d, actual %d"
 
@@ -406,7 +387,7 @@ mysql_lease6_dump_test() {
     mysql_wipe
 
     # Ok, now let's initalize the database
-    ${keaadmin} lease-init mysql -u $db_user -p $db_password -n $db_name -d $script_dir
+    ${keaadmin} lease-init mysql -u $db_user -p $db_password -n $db_name -d $db_scripts_dir
     ERRCODE=$?
     assert_eq 0 $ERRCODE "could not create database, expected exit code %d, actual %d"
 
@@ -421,7 +402,7 @@ insert into lease6 values(12,21,30,\"2015-06-06 11:01:07\",40,50,1,60,70,1,1,\"t
     assert_eq 0 $ERRCODE "insert into lease6 failed, expected exit code %d, actual %d"
 
     # Dump lease4 to output_file
-    ${keaadmin} lease-dump mysql -6 -u $db_user -p $db_password -n $db_name -d $script_dir -o $output_file
+    ${keaadmin} lease-dump mysql -6 -u $db_user -p $db_password -n $db_name -d $db_scripts_dir -o $output_file
     ERRCODE=$?
     assert_eq 0 $ERRCODE "kea-admin lease-dump -6 failed, status code %d"
 

+ 15 - 27
src/bin/admin/tests/pgsql_tests.sh.in

@@ -1,6 +1,6 @@
 #!/bin/sh
 
-# Copyright (C) 2015 Internet Systems Consortium, Inc. ("ISC")
+# Copyright (C) 2015-2016 Internet Systems Consortium, Inc. ("ISC")
 #
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
@@ -9,15 +9,11 @@
 # Include common test library.
 . @abs_top_builddir@/src/lib/testutils/dhcp_test_lib.sh
 
-# If the code is installed, include admin-utils.sh from the destination
-# directory. If not, include it from the sources.
-prefix=@prefix@
+# Include admin utilities
+. @abs_top_srcdir@/src/bin/admin/admin-utils.sh
 
-if [ -e @datarootdir@/@PACKAGE_NAME@/scripts/admin-utils.sh ]; then
-    . @datarootdir@/@PACKAGE_NAME@/scripts/admin-utils.sh
-else
-    . @abs_top_srcdir@/src/bin/admin/admin-utils.sh
-fi
+# Set path to the production schema scripts
+db_scripts_dir=@abs_top_srcdir@/src/share/database/scripts
 
 db_user="keatest"
 db_password="keatest"
@@ -26,21 +22,13 @@ db_name="keatest"
 # Set location of the kea-admin.
 keaadmin=@abs_top_builddir@/src/bin/admin/kea-admin
 
-# Set location of scripts directory
-scripts_dir=@abs_top_srcdir@/src/bin/admin/scripts
-
 # Wipe all tables from the DB:
 pgsql_wipe() {
     printf "Wiping whole database %s\n" $db_name
     export PGPASSWORD=$db_password
 
-    # Make a set of drop commands, one for each table owned by keatest
-    RESULT=`pgsql_execute "SELECT 'drop table if exists '||t.tablename || ' cascade;' as dcmd FROM pg_catalog.pg_tables t WHERE t.tableowner = 'keatest';"`
-    assert_eq 0 $? "pgsql_wipe select failed, expected exit code: %d, actual: %d"
-
-    # Now execute the set of drop commands from the result set returned
-    RESULT=`pgsql_execute "$RESULT"`
-    assert_eq 0 $? "pgsql_wipe drop failed, expected exit code: %d, actual: %d"
+    cat $db_scripts_dir/pgsql/dhcpdb_drop.pgsql | psql --set ON_ERROR_STOP=1 -A -t -q -U keatest -d keatest >/dev/null 2>&1
+    assert_eq 0 $?  "pgsql_wipe drop failed, expected exit code: %d, actual: %d"
 }
 
 pgsql_lease_init_test() {
@@ -50,7 +38,7 @@ pgsql_lease_init_test() {
     pgsql_wipe
 
     # Create the database
-    ${keaadmin} lease-init pgsql -u $db_user -p $db_password -n $db_name -d $scripts_dir
+    ${keaadmin} lease-init pgsql -u $db_user -p $db_password -n $db_name -d $db_scripts_dir
     assert_eq 0 $? "kea-admin lease-init pgsql failed, expected exit code: %d, actual: %d"
 
     # Verify that all the expected tables exist
@@ -79,7 +67,7 @@ pgsql_lease_init_test() {
     # check
     echo ""
     echo "DB created successfully, make sure we aren't allowed to try it again:"
-    ${keaadmin} lease-init pgsql -u $db_user -p $db_password -n $db_name -d $scripts_dir
+    ${keaadmin} lease-init pgsql -u $db_user -p $db_password -n $db_name -d $db_scripts_dir
     assert_eq 2 $? "kea-admin failed to deny lease-init, expected exit code: %d, actual: %d"
 
     # Let's wipe the whole database
@@ -95,7 +83,7 @@ pgsql_lease_version_test() {
     pgsql_wipe
 
     # Create the database
-    ${keaadmin} lease-init pgsql -u $db_user -p $db_password -n $db_name -d $scripts_dir
+    ${keaadmin} lease-init pgsql -u $db_user -p $db_password -n $db_name -d $db_scripts_dir
     assert_eq 0 $? "cannot initialize the database, expected exit code: %d, actual: %d"
 
     # Verfiy that kea-admin lease-version returns the correct version
@@ -118,7 +106,7 @@ pgsql_upgrade_test() {
     pgsql_execute_script @abs_top_srcdir@/src/bin/admin/tests/dhcpdb_create_1.0.pgsql
     assert_eq 0 $? "cannot initialize the database, expected exit code: %d, actual: %d"
 
-    ${keaadmin} lease-upgrade pgsql -u $db_user -p $db_password -n $db_name -d $scripts_dir
+    ${keaadmin} lease-upgrade pgsql -u $db_user -p $db_password -n $db_name -d $db_scripts_dir
     assert_eq 0 $? "lease-upgrade failed, expected exit code: %d, actual: %d"
 
     #table: state column added to lease4 (upgrade 1.0 -> 2.0)
@@ -204,7 +192,7 @@ pgsql_lease4_dump_test() {
     pgsql_wipe
 
     # Ok, now let's initalize the database
-    ${keaadmin} lease-init pgsql -u $db_user -p $db_password -n $db_name -d $script_dir
+    ${keaadmin} lease-init pgsql -u $db_user -p $db_password -n $db_name -d $db_scripts_dir
     ERRCODE=$?
     assert_eq 0 $ERRCODE "could not create database, expected exit code %d, actual %d"
 
@@ -223,7 +211,7 @@ insert into lease4 values(12,E'\\x22','',40,'$timestamp3',50,'t','t','three.exam
     assert_eq 0 $ERRCODE "insert into lease4 failed, expected exit code %d, actual %d"
 
     # Dump lease4 to output_file
-    ${keaadmin} lease-dump pgsql -4 -u $db_user -p $db_password -n $db_name -d $script_dir -o $output_file
+    ${keaadmin} lease-dump pgsql -4 -u $db_user -p $db_password -n $db_name -d $db_scripts_dir -o $output_file
     ERRCODE=$?
     assert_eq 0 $ERRCODE "kea-admin lease-dump -4 failed,  status code %d"
 
@@ -299,7 +287,7 @@ pgsql_lease6_dump_test() {
     pgsql_wipe
 
     # Ok, now let's initalize the database
-    ${keaadmin} lease-init pgsql -u $db_user -p $db_password -n $db_name -d $script_dir
+    ${keaadmin} lease-init pgsql -u $db_user -p $db_password -n $db_name -d $db_scripts_dir
     ERRCODE=$?
     assert_eq 0 $ERRCODE "could not create database,  status code %d"
 
@@ -318,7 +306,7 @@ insert into lease6 values(12,E'\\x21',30,'$timestamp3',40,50,1,60,70,'t','t','th
     assert_eq 0 $ERRCODE "insert into lease6 failed, status code %d"
 
     # Dump lease6 to output_file
-    ${keaadmin} lease-dump pgsql -6 -u $db_user -p $db_password -n $db_name -d $script_dir -o $output_file
+    ${keaadmin} lease-dump pgsql -6 -u $db_user -p $db_password -n $db_name -d $db_scripts_dir -o $output_file
     ERRCODE=$?
     assert_eq 0 $ERRCODE "kea-admin lease-dump -6 failed, status code %d"
 

+ 50 - 11
src/lib/dhcpsrv/pgsql_lease_mgr.cc

@@ -1,4 +1,4 @@
-// Copyright (C) 2014-2015 Internet Systems Consortium, Inc. ("ISC")
+// Copyright (C) 2014-2016 Internet Systems Consortium, Inc. ("ISC")
 //
 // This Source Code Form is subject to the terms of the Mozilla Public
 // License, v. 2.0. If a copy of the MPL was not distributed with this
@@ -417,7 +417,7 @@ public:
         return (value);
     }
 
-    /// @brief Converts a column in a row in a result set to a boolean.
+    /// @brief Fetches boolean text ('t' or 'f') as a bool.
     ///
     /// @param r the result set containing the query results
     /// @param row the row number within the result set
@@ -440,7 +440,7 @@ public:
         }
     }
 
-    /// @brief Converts a column in a row in a result set to a uint32_t.
+    /// @brief Fetches an integer text column as a uint32_t.
     ///
     /// @param r the result set containing the query results
     /// @param row the row number within the result set
@@ -461,7 +461,28 @@ public:
         }
     }
 
-    /// @brief Converts a column in a row in a result set to a uint8_t.
+    /// @brief Fetches an integer text column as a int32_t.
+    ///
+    /// @param r the result set containing the query results
+    /// @param row the row number within the result set
+    /// @param col the column number within the row
+    /// @param[out] value parameter to receive the converted value
+    ///
+    /// @throw  DbOperationError if the value cannot be fetched or is
+    /// invalid.
+    void getColumnValue(PGresult*& r, const int row, const size_t col,
+                        int32_t &value) const {
+        const char* data = getRawColumnValue(r, row, col);
+        try {
+            value = boost::lexical_cast<int32_t>(data);
+        } catch (const std::exception& ex) {
+            isc_throw(DbOperationError, "Invalid int32_t data: " << data
+                      << " for: " << getColumnLabel(col) << " row:" << row
+                      << " : " << ex.what());
+        }
+    }
+
+    /// @brief Fetches an integer text column as a uint8_t.
     ///
     /// @param r the result set containing the query results
     /// @param row the row number within the result set
@@ -484,7 +505,7 @@ public:
         }
     }
 
-    /// @brief Converts a column in a row in a result set to a Lease6::Type
+    /// @brief Fetches an integer text column as a Lease6::Type
     ///
     /// @param r the result set containing the query results
     /// @param row the row number within the result set
@@ -807,7 +828,7 @@ private:
 
 public:
     PgSqlLease6Exchange()
-        : lease_(), duid_length_(0), duid_(), iaid_(0), iaid_str_(""),
+        : lease_(), duid_length_(0), duid_(), iaid_u_(0), iaid_str_(""),
           lease_type_(Lease6::TYPE_NA), lease_type_str_(""), prefix_len_(0),
           prefix_len_str_(""), pref_lifetime_(0), preferred_lft_str_("") {
 
@@ -878,7 +899,11 @@ public:
             lease_type_str_ = boost::lexical_cast<std::string>(lease_->type_);
             bind_array.add(lease_type_str_);
 
-            iaid_str_ = boost::lexical_cast<std::string>(lease_->iaid_);
+            // The iaid is stored as an INT in lease6 table, so we must
+            // lexically cast from an integer version to avoid out of range
+            // exception failure upon insert.
+            iaid_u_.uval_ = lease_->iaid_;
+            iaid_str_ = boost::lexical_cast<std::string>(iaid_u_.ival_);
             bind_array.add(iaid_str_);
 
             prefix_len_str_ = boost::lexical_cast<std::string>
@@ -930,7 +955,7 @@ public:
 
             getColumnValue(r, row, LEASE_TYPE_COL, lease_type_);
 
-            getColumnValue(r, row , IAID_COL, iaid_);
+            getColumnValue(r, row , IAID_COL, iaid_u_.ival_);
 
             getColumnValue(r, row , PREFIX_LEN_COL, prefix_len_);
 
@@ -942,8 +967,9 @@ public:
             /// @todo: implement this in #3557.
             HWAddrPtr hwaddr;
 
-            Lease6Ptr result(new Lease6(lease_type_, addr, duid_ptr, iaid_,
-                                        pref_lifetime_, valid_lifetime_, 0, 0,
+            Lease6Ptr result(new Lease6(lease_type_, addr, duid_ptr,
+                                        iaid_u_.uval_, pref_lifetime_,
+                                        valid_lifetime_, 0, 0,
                                         subnet_id_, fqdn_fwd_, fqdn_rev_,
                                         hostname_, hwaddr, prefix_len_));
             result->cltt_ = cltt_;
@@ -987,7 +1013,20 @@ private:
     size_t          duid_length_;
     vector<uint8_t> duid_;
     uint8_t         duid_buffer_[DUID::MAX_DUID_LEN];
-    uint32_t        iaid_;
+
+    /// @brief Union for marshalling IAID into and out of the database
+    /// IAID is defined in the RFC as 4 octets, which Kea code handles as
+    /// a uint32_t.  Postgresql however, offers only signed integer types
+    /// of sizes 2, 4, and 8 bytes (SMALLINT, INT, and BIGINT respectively).
+    /// IAID is used in several indexes so rather than use the BIGINT, we
+    /// use this union to safely move the value into and out of an INT column.
+    union Uiaid {
+        Uiaid(uint32_t val) : uval_(val){};
+        Uiaid(int32_t val) : ival_(val){};
+        uint32_t uval_;
+        int32_t ival_;
+    } iaid_u_;
+
     std::string iaid_str_;
     Lease6::Type    lease_type_;
     std::string lease_type_str_;

+ 0 - 1
src/lib/dhcpsrv/tests/Makefile.am

@@ -115,7 +115,6 @@ if HAVE_PGSQL
 libdhcpsrv_unittests_SOURCES += pgsql_lease_mgr_unittest.cc
 endif
 libdhcpsrv_unittests_SOURCES += pool_unittest.cc
-libdhcpsrv_unittests_SOURCES += schema_pgsql_copy.h
 libdhcpsrv_unittests_SOURCES += srv_config_unittest.cc
 libdhcpsrv_unittests_SOURCES += subnet_unittest.cc
 libdhcpsrv_unittests_SOURCES += test_get_callout_handle.cc test_get_callout_handle.h

+ 5 - 5
src/lib/dhcpsrv/tests/generic_lease_mgr_unittest.cc

@@ -1,4 +1,4 @@
-// Copyright (C) 2014-2015 Internet Systems Consortium, Inc. ("ISC")
+// Copyright (C) 2014-2016 Internet Systems Consortium, Inc. ("ISC")
 //
 // This Source Code Form is subject to the terms of the Mozilla Public
 // License, v. 2.0. If a copy of the MPL was not distributed with this
@@ -916,8 +916,8 @@ GenericLeaseMgrTest::testLease6HWTypeAndSource() {
 
     // Those should use defines from Pkt::HWADDR_SOURCE_*, but let's
     // test an uncommon value (and 0 which means unknown).
-    hwaddr1->source_ = 123456u;
-    hwaddr2->source_ = 0;
+    hwaddr1->source_ = HWAddr::HWADDR_SOURCE_RAW;
+    hwaddr2->source_ = HWAddr::HWADDR_SOURCE_DUID;
 
     leases[1]->hwaddr_ = hwaddr1;     // Add hardware address to leases 1 and 2
     leases[2]->hwaddr_ = hwaddr2;
@@ -938,14 +938,14 @@ GenericLeaseMgrTest::testLease6HWTypeAndSource() {
     ASSERT_TRUE(stored1);
     ASSERT_TRUE(stored1->hwaddr_);
     EXPECT_EQ(123, stored1->hwaddr_->htype_);
-    EXPECT_EQ(123456, stored1->hwaddr_->source_);
+    EXPECT_EQ(HWAddr::HWADDR_SOURCE_RAW, stored1->hwaddr_->source_);
 
     // Second lease should have a hardware address in it
     Lease6Ptr stored2 = lmptr_->getLease6(leasetype6_[2], ioaddress6_[2]);
     ASSERT_TRUE(stored2);
     ASSERT_TRUE(stored2->hwaddr_);
     EXPECT_EQ(456, stored2->hwaddr_->htype_);
-    EXPECT_EQ(0, stored2->hwaddr_->source_);
+    EXPECT_EQ(HWAddr::HWADDR_SOURCE_DUID, stored2->hwaddr_->source_);
 
     // Third lease should NOT have any hardware address.
     Lease6Ptr stored3 = lmptr_->getLease6(leasetype6_[3], ioaddress6_[3]);

+ 5 - 5
src/lib/dhcpsrv/tests/mysql_host_data_source_unittest.cc

@@ -125,21 +125,21 @@ TEST(MySqlHostDataSource, OpenDatabase) {
 
     // Check that invalid login data causes an exception.
     EXPECT_THROW(HostDataSourceFactory::create(connectionString(
-        VALID_TYPE, INVALID_NAME, VALID_HOST, VALID_USER, VALID_PASSWORD)),
+        MYSQL_VALID_TYPE, INVALID_NAME, VALID_HOST, VALID_USER, VALID_PASSWORD)),
         DbOpenError);
     EXPECT_THROW(HostDataSourceFactory::create(connectionString(
-        VALID_TYPE, VALID_NAME, INVALID_HOST, VALID_USER, VALID_PASSWORD)),
+        MYSQL_VALID_TYPE, VALID_NAME, INVALID_HOST, VALID_USER, VALID_PASSWORD)),
         DbOpenError);
     EXPECT_THROW(HostDataSourceFactory::create(connectionString(
-        VALID_TYPE, VALID_NAME, VALID_HOST, INVALID_USER, VALID_PASSWORD)),
+        MYSQL_VALID_TYPE, VALID_NAME, VALID_HOST, INVALID_USER, VALID_PASSWORD)),
         DbOpenError);
     EXPECT_THROW(HostDataSourceFactory::create(connectionString(
-        VALID_TYPE, VALID_NAME, VALID_HOST, VALID_USER, INVALID_PASSWORD)),
+        MYSQL_VALID_TYPE, VALID_NAME, VALID_HOST, VALID_USER, INVALID_PASSWORD)),
         DbOpenError);
 
     // Check for missing parameters
     EXPECT_THROW(HostDataSourceFactory::create(connectionString(
-        VALID_TYPE, NULL, VALID_HOST, INVALID_USER, VALID_PASSWORD)),
+        MYSQL_VALID_TYPE, NULL, VALID_HOST, INVALID_USER, VALID_PASSWORD)),
         NoDatabaseName);
 
     // Tidy up after the test

+ 8 - 8
src/lib/dhcpsrv/tests/mysql_lease_mgr_unittest.cc

@@ -97,8 +97,8 @@ public:
 TEST(MySqlOpenTest, OpenDatabase) {
 
     // Schema needs to be created for the test to work.
-    destroyMySQLSchema();
-    createMySQLSchema();
+    destroyMySQLSchema(true);
+    createMySQLSchema(true);
 
     // Check that lease manager open the database opens correctly and tidy up.
     //  If it fails, print the error message.
@@ -129,25 +129,25 @@ TEST(MySqlOpenTest, OpenDatabase) {
 
     // Check that invalid login data causes an exception.
     EXPECT_THROW(LeaseMgrFactory::create(connectionString(
-        VALID_TYPE, INVALID_NAME, VALID_HOST, VALID_USER, VALID_PASSWORD)),
+        MYSQL_VALID_TYPE, INVALID_NAME, VALID_HOST, VALID_USER, VALID_PASSWORD)),
         DbOpenError);
     EXPECT_THROW(LeaseMgrFactory::create(connectionString(
-        VALID_TYPE, VALID_NAME, INVALID_HOST, VALID_USER, VALID_PASSWORD)),
+        MYSQL_VALID_TYPE, VALID_NAME, INVALID_HOST, VALID_USER, VALID_PASSWORD)),
         DbOpenError);
     EXPECT_THROW(LeaseMgrFactory::create(connectionString(
-        VALID_TYPE, VALID_NAME, VALID_HOST, INVALID_USER, VALID_PASSWORD)),
+        MYSQL_VALID_TYPE, VALID_NAME, VALID_HOST, INVALID_USER, VALID_PASSWORD)),
         DbOpenError);
     EXPECT_THROW(LeaseMgrFactory::create(connectionString(
-        VALID_TYPE, VALID_NAME, VALID_HOST, VALID_USER, INVALID_PASSWORD)),
+        MYSQL_VALID_TYPE, VALID_NAME, VALID_HOST, VALID_USER, INVALID_PASSWORD)),
         DbOpenError);
 
     // Check for missing parameters
     EXPECT_THROW(LeaseMgrFactory::create(connectionString(
-        VALID_TYPE, NULL, VALID_HOST, INVALID_USER, VALID_PASSWORD)),
+        MYSQL_VALID_TYPE, NULL, VALID_HOST, INVALID_USER, VALID_PASSWORD)),
         NoDatabaseName);
 
     // Tidy up after the test
-    destroyMySQLSchema();
+    destroyMySQLSchema(true);
 }
 
 /// @brief Check the getType() method

+ 18 - 127
src/lib/dhcpsrv/tests/pgsql_lease_mgr_unittest.cc

@@ -1,4 +1,4 @@
-// Copyright (C) 2014-2015 Internet Systems Consortium, Inc. ("ISC")
+// Copyright (C) 2014-2016 Internet Systems Consortium, Inc. ("ISC")
 //
 // This Source Code Form is subject to the terms of the Mozilla Public
 // License, v. 2.0. If a copy of the MPL was not distributed with this
@@ -11,9 +11,9 @@
 #include <dhcpsrv/pgsql_lease_mgr.h>
 #include <dhcpsrv/tests/test_utils.h>
 #include <dhcpsrv/tests/generic_lease_mgr_unittest.h>
+#include <dhcpsrv/testutils/pgsql_schema.h>
 #include <exceptions/exceptions.h>
 
-
 #include <gtest/gtest.h>
 
 #include <algorithm>
@@ -22,6 +22,8 @@
 #include <string>
 #include <utility>
 
+#include <stdlib.h>
+
 using namespace isc;
 using namespace isc::asiolink;
 using namespace isc::dhcp;
@@ -30,112 +32,6 @@ using namespace std;
 
 namespace {
 
-// This holds statements to create and destroy the schema.
-#include "schema_pgsql_copy.h"
-
-// Connection strings.
-// Database: keatest
-// Host: localhost
-// Username: keatest
-// Password: keatest
-const char* VALID_TYPE = "type=postgresql";
-const char* INVALID_TYPE = "type=unknown";
-const char* VALID_NAME = "name=keatest";
-const char* INVALID_NAME = "name=invalidname";
-const char* VALID_HOST = "host=localhost";
-const char* INVALID_HOST = "host=invalidhost";
-const char* VALID_USER = "user=keatest";
-const char* INVALID_USER = "user=invaliduser";
-const char* VALID_PASSWORD = "password=keatest";
-const char* INVALID_PASSWORD = "password=invalid";
-
-// Given a combination of strings above, produce a connection string.
-string connectionString(const char* type, const char* name, const char* host,
-                        const char* user, const char* password) {
-    const string space = " ";
-    string result = "";
-
-    if (type != NULL) {
-        result += string(type);
-    }
-    if (name != NULL) {
-        if (! result.empty()) {
-            result += space;
-        }
-        result += string(name);
-    }
-
-    if (host != NULL) {
-        if (! result.empty()) {
-            result += space;
-        }
-        result += string(host);
-    }
-
-    if (user != NULL) {
-        if (! result.empty()) {
-            result += space;
-        }
-        result += string(user);
-    }
-
-    if (password != NULL) {
-        if (! result.empty()) {
-            result += space;
-        }
-        result += string(password);
-    }
-
-    return (result);
-}
-
-// Return valid connection string
-string
-validConnectionString() {
-    return (connectionString(VALID_TYPE, VALID_NAME, VALID_HOST,
-                             VALID_USER, VALID_PASSWORD));
-}
-
-// @brief Clear everything from the database
-//
-// There is no error checking in this code: if something fails, one of the
-// tests will (should) fall over.
-void destroySchema() {
-    // Open database
-    PGconn* conn = 0;
-    conn = PQconnectdb("host = 'localhost' user = 'keatest'"
-                       " password = 'keatest' dbname = 'keatest'");
-
-    // Get rid of everything in it.
-    for (int i = 0; destroy_statement[i] != NULL; ++i) {
-        PGresult* r = PQexec(conn, destroy_statement[i]);
-        PQclear(r);
-    }
-
-    PQfinish(conn);
-}
-
-// @brief Create the Schema
-//
-// Creates all the tables in what is assumed to be an empty database.
-//
-// There is no error checking in this code: if it fails, one of the tests
-// will fall over.
-void createSchema() {
-    // Open database
-    PGconn* conn = 0;
-    conn = PQconnectdb("host = 'localhost' user = 'keatest'"
-                       " password = 'keatest' dbname = 'keatest'");
-
-    // Get rid of everything in it.
-    for (int i = 0; create_statement[i] != NULL; ++i) {
-        PGresult* r = PQexec(conn, create_statement[i]);
-        PQclear(r);
-    }
-
-    PQfinish(conn);
-}
-
 /// @brief Test fixture class for testing PostgreSQL Lease Manager
 ///
 /// Opens the database prior to each test and closes it afterwards.
@@ -149,12 +45,12 @@ public:
     PgSqlLeaseMgrTest() {
 
         // Ensure schema is the correct one.
-        destroySchema();
-        createSchema();
+        destroyPgSQLSchema();
+        createPgSQLSchema();
 
         // Connect to the database
         try {
-            LeaseMgrFactory::create(validConnectionString());
+            LeaseMgrFactory::create(validPgSQLConnectionString());
         } catch (...) {
             std::cerr << "*** ERROR: unable to open database. The test\n"
                          "*** environment is broken and must be fixed before\n"
@@ -173,7 +69,7 @@ public:
     virtual ~PgSqlLeaseMgrTest() {
         lmptr_->rollback();
         LeaseMgrFactory::destroy();
-        destroySchema();
+        destroyPgSQLSchema();
     }
 
     /// @brief Reopen the database
@@ -185,7 +81,7 @@ public:
     /// the same database.
     void reopen(Universe) {
         LeaseMgrFactory::destroy();
-        LeaseMgrFactory::create(validConnectionString());
+        LeaseMgrFactory::create(validPgSQLConnectionString());
         lmptr_ = &(LeaseMgrFactory::instance());
     }
 
@@ -201,13 +97,13 @@ public:
 TEST(PgSqlOpenTest, OpenDatabase) {
 
     // Schema needs to be created for the test to work.
-    destroySchema();
-    createSchema();
+    destroyPgSQLSchema(true);
+    createPgSQLSchema(true);
 
     // Check that lease manager open the database opens correctly and tidy up.
     //  If it fails, print the error message.
     try {
-        LeaseMgrFactory::create(validConnectionString());
+        LeaseMgrFactory::create(validPgSQLConnectionString());
         EXPECT_NO_THROW((void) LeaseMgrFactory::instance());
         LeaseMgrFactory::destroy();
     } catch (const isc::Exception& ex) {
@@ -233,31 +129,31 @@ TEST(PgSqlOpenTest, OpenDatabase) {
 
     // Check that invalid login data causes an exception.
     EXPECT_THROW(LeaseMgrFactory::create(connectionString(
-        VALID_TYPE, INVALID_NAME, VALID_HOST, VALID_USER, VALID_PASSWORD)),
+        PGSQL_VALID_TYPE, INVALID_NAME, VALID_HOST, VALID_USER, VALID_PASSWORD)),
         DbOpenError);
 
     EXPECT_THROW(LeaseMgrFactory::create(connectionString(
-        VALID_TYPE, VALID_NAME, INVALID_HOST, VALID_USER, VALID_PASSWORD)),
+        PGSQL_VALID_TYPE, VALID_NAME, INVALID_HOST, VALID_USER, VALID_PASSWORD)),
         DbOpenError);
 
     EXPECT_THROW(LeaseMgrFactory::create(connectionString(
-        VALID_TYPE, VALID_NAME, VALID_HOST, INVALID_USER, VALID_PASSWORD)),
+        PGSQL_VALID_TYPE, VALID_NAME, VALID_HOST, INVALID_USER, VALID_PASSWORD)),
         DbOpenError);
 
     // This test might fail if 'auth-method' in PostgresSQL host-based authentication
     // file (/var/lib/pgsql/9.4/data/pg_hba.conf) is set to 'trust',
     // which allows logging without password. 'Auth-method' should be changed to 'password'.
     EXPECT_THROW(LeaseMgrFactory::create(connectionString(
-        VALID_TYPE, VALID_NAME, VALID_HOST, VALID_USER, INVALID_PASSWORD)),
+        PGSQL_VALID_TYPE, VALID_NAME, VALID_HOST, VALID_USER, INVALID_PASSWORD)),
         DbOpenError);
 
     // Check for missing parameters
     EXPECT_THROW(LeaseMgrFactory::create(connectionString(
-        VALID_TYPE, NULL, VALID_HOST, INVALID_USER, VALID_PASSWORD)),
+        PGSQL_VALID_TYPE, NULL, VALID_HOST, INVALID_USER, VALID_PASSWORD)),
         NoDatabaseName);
 
     // Tidy up after the test
-    destroySchema();
+    destroyPgSQLSchema(true);
 }
 
 /// @brief Check the getType() method
@@ -490,9 +386,4 @@ TEST_F(PgSqlLeaseMgrTest, getExpiredLeases6) {
     testGetExpiredLeases6();
 }
 
-/// @brief Check that expired reclaimed DHCPv6 leases are removed.
-TEST_F(PgSqlLeaseMgrTest, deleteExpiredReclaimedLeases6) {
-    testDeleteExpiredReclaimedLeases6();
-}
-
 };

+ 0 - 129
src/lib/dhcpsrv/tests/schema_pgsql_copy.h

@@ -1,129 +0,0 @@
-// Copyright (C) 2014-2015 Internet Systems Consortium, Inc. ("ISC")
-//
-// This Source Code Form is subject to the terms of the Mozilla Public
-// License, v. 2.0. If a copy of the MPL was not distributed with this
-// file, You can obtain one at http://mozilla.org/MPL/2.0/.
-
-#ifndef SCHEMA_COPY_H
-#define SCHEMA_COPY_H
-
-namespace {
-
-// What follows is a set of statements that creates a copy of the schema
-// in the test database.  It is used by the PostgreSQL unit test prior to each
-// test.
-//
-// Each SQL statement is a single string.  The statements are not terminated
-// by semicolons, and the strings must end with a comma.  The final line
-// statement must be NULL (not in quotes)
-
-// NOTE: This file mirrors the schema in src/lib/dhcpsrv/dhcpdb_create.pgsql.
-//       If this file is altered, please ensure that any change is compatible
-//       with the schema in dhcpdb_create.pgsql.
-
-// Deletion of existing tables.
-
-const char* destroy_statement[] = {
-    "DROP TABLE lease4",
-    "DROP TABLE lease6",
-    "DROP TABLE lease6_types",
-    "DROP TABLE schema_version",
-    NULL
-};
-
-// Creation of the new tables.
-
-const char* create_statement[] = {
-    "START TRANSACTION",
-    "CREATE TABLE lease4 ("
-    "address BIGINT PRIMARY KEY NOT NULL,"
-    "hwaddr BYTEA,"
-    "client_id BYTEA,"
-    "valid_lifetime BIGINT,"
-    "expire TIMESTAMP WITH TIME ZONE,"
-    "subnet_id BIGINT,"
-    "fqdn_fwd BOOLEAN,"
-    "fqdn_rev BOOLEAN,"
-    "hostname VARCHAR(255)"
-    ")",
-
-    "CREATE TABLE lease6 ("
-    "address VARCHAR(39) PRIMARY KEY NOT NULL,"
-    "duid BYTEA,"
-    "valid_lifetime BIGINT,"
-    "expire TIMESTAMP WITH TIME ZONE,"
-    "subnet_id BIGINT,"
-    "pref_lifetime BIGINT,"
-    "lease_type SMALLINT,"
-    "iaid BIGINT,"
-    "prefix_len SMALLINT,"
-    "fqdn_fwd BOOLEAN,"
-    "fqdn_rev BOOLEAN,"
-    "hostname VARCHAR(255)"
-    ")",
-
-    "CREATE TABLE lease6_types ("
-    "lease_type SMALLINT PRIMARY KEY NOT NULL,"
-    "name VARCHAR(5)"
-    ")",
-
-    "INSERT INTO lease6_types VALUES (0, 'IA_NA')",
-    "INSERT INTO lease6_types VALUES (1, 'IA_TA')",
-    "INSERT INTO lease6_types VALUES (2, 'IA_PD')",
-
-    "CREATE TABLE schema_version ("
-        "version INT PRIMARY KEY NOT NULL,"
-        "minor INT"
-        ")",
-
-    "INSERT INTO schema_version VALUES (1, 0)",
-    "COMMIT",
-
-    // This line concludes creation of database version 1.0.
-
-    // Schema upgrade to 2.0 starts here.
-
-    "ALTER TABLE lease4 "
-        "ADD COLUMN state INT8 DEFAULT 0",
-
-    "ALTER TABLE lease6 "
-        "ADD COLUMN state INT8 DEFAULT 0",
-
-    "CREATE INDEX lease4_by_state_expire ON lease4 (state ASC, expire ASC)",
-    "CREATE INDEX lease6_by_state_expire ON lease6 (state ASC, expire ASC)",
-
-    // Production schema includes the lease_state table which maps
-    // the lease states to their names. This is not used in the unit tests
-    // so it is commented out.
-
-    /*"CREATE TABLE lease_state (",
-        "state INT8 PRIMARY KEY NOT NULL,"
-        "name VARCHAR(64) NOT NULL);",
-
-    "ALTER TABLE lease4 "
-        "ADD CONSTRAINT fk_lease4_state FOREIGN KEY (state) "
-        "REFERENCES lease_state (state)",
-
-    "ALTER TABLE lease6 "
-        "ADD CONSTRAINT fk_lease6_state FOREIGN KEY (state) "
-        "REFERENCES lease_state (state)",
-
-    "ALTER TABLE lease6 "
-        "ADD CONSTRAINT fk_lease6_type FOREIGN KEY (lease_type) "
-        "REFERENCES lease6_types (lease_type)",
-
-    "INSERT INTO lease_state VALUES (0, \"default\");",
-    "INSERT INTO lease_state VALUES (1, \"declined\");",
-    "INSERT INTO lease_state VALUES (2, \"expired-reclaimed\");",*/
-
-    "UPDATE schema_version SET version = '2', minor = '0';",
-    "COMMIT",
-
-    // Schema upgrade to 2.0 ends here.
-
-    NULL
-};
-
-};  // Anonymous namespace
-
-#endif // SCHEMA_COPY_H

+ 22 - 2
src/lib/dhcpsrv/testutils/Makefile.am

@@ -1,6 +1,7 @@
 SUBDIRS = .
 
 AM_CPPFLAGS = -I$(top_builddir)/src/lib -I$(top_srcdir)/src/lib
+AM_CPPFLAGS += -DDATABASE_SCRIPTS_DIR=\"$(abs_top_srcdir)/src/share/database/scripts\"
 AM_CPPFLAGS += $(BOOST_INCLUDES)
 
 AM_CXXFLAGS = $(KEA_CXXFLAGS)
@@ -11,10 +12,21 @@ if HAVE_GTEST
 
 noinst_LTLIBRARIES = libdhcpsrvtest.la
 
-libdhcpsrvtest_la_SOURCES  = config_result_check.cc config_result_check.h
+libdhcpsrvtest_la_SOURCES = config_result_check.cc config_result_check.h
+
+if HAVE_MYSQL
+libdhcpsrvtest_la_SOURCES += schema.cc schema.h
+else
+if HAVE_PGSQL
+libdhcpsrvtest_la_SOURCES += schema.cc schema.h
+endif
+endif
+
 if HAVE_MYSQL
 libdhcpsrvtest_la_SOURCES += mysql_schema.cc mysql_schema.h
-libdhcpsrvtest_la_SOURCES += schema_mysql_copy.h
+endif
+if HAVE_PGSQL
+libdhcpsrvtest_la_SOURCES += pgsql_schema.cc pgsql_schema.h
 endif
 
 libdhcpsrvtest_la_CXXFLAGS = $(AM_CXXFLAGS)
@@ -22,10 +34,18 @@ libdhcpsrvtest_la_CPPFLAGS = $(AM_CPPFLAGS) $(GTEST_INCLUDES)
 if HAVE_MYSQL
 libdhcpsrvtest_la_CPPFLAGS += $(MYSQL_CPPFLAGS)
 endif
+if HAVE_PGSQL
+libdhcpsrvtest_la_CPPFLAGS += $(PGSQL_CPPFLAGS)
+endif
+
 libdhcpsrvtest_la_LDFLAGS  = $(AM_LDFLAGS)
 if HAVE_MYSQL
 libdhcpsrvtest_la_LDFLAGS  += $(MYSQL_LIBS)
 endif
+if HAVE_PGSQL
+libdhcpsrvtest_la_LDFLAGS  += $(PGSQL_LIBS)
+endif
+
 libdhcpsrvtest_la_LIBADD   = $(top_builddir)/src/lib/cc/libkea-cc.la
 libdhcpsrvtest_la_LIBADD  += $(top_builddir)/src/lib/log/libkea-log.la
 

+ 27 - 90
src/lib/dhcpsrv/testutils/mysql_schema.cc

@@ -1,4 +1,4 @@
-// Copyright (C) 2015 Internet Systems Consortium, Inc. ("ISC")
+// Copyright (C) 2015-2016 Internet Systems Consortium, Inc. ("ISC")
 //
 // This Source Code Form is subject to the terms of the Mozilla Public
 // License, v. 2.0. If a copy of the MPL was not distributed with this
@@ -8,10 +8,12 @@
 #include <string>
 #include <mysql.h>
 #include <dhcpsrv/mysql_connection.h>
+#include <dhcpsrv/testutils/mysql_schema.h>
 #include <gtest/gtest.h>
 
-// This holds statements to create and destroy the schema.
-#include "schema_mysql_copy.h"
+#include <fstream>
+#include <sstream>
+#include <stdlib.h>
 
 using namespace std;
 
@@ -19,107 +21,42 @@ namespace isc {
 namespace dhcp {
 namespace test {
 
-// Connection strings.
-// Database: keatest
-// Host: localhost
-// Username: keatest
-// Password: keatest
-const char* VALID_TYPE = "type=mysql";
-const char* INVALID_TYPE = "type=unknown";
-const char* VALID_NAME = "name=keatest";
-const char* INVALID_NAME = "name=invalidname";
-const char* VALID_HOST = "host=localhost";
-const char* INVALID_HOST = "host=invalidhost";
-const char* VALID_USER = "user=keatest";
-const char* INVALID_USER = "user=invaliduser";
-const char* VALID_PASSWORD = "password=keatest";
-const char* INVALID_PASSWORD = "password=invalid";
+const char* MYSQL_VALID_TYPE = "type=mysql";
 
-string connectionString(const char* type, const char* name, const char* host,
-                        const char* user, const char* password) {
-    const string space = " ";
-    string result = "";
-
-    if (type != NULL) {
-        result += string(type);
-    }
-    if (name != NULL) {
-        if (! result.empty()) {
-            result += space;
-        }
-        result += string(name);
-    }
-
-    if (host != NULL) {
-        if (! result.empty()) {
-            result += space;
-        }
-        result += string(host);
-    }
-
-    if (user != NULL) {
-        if (! result.empty()) {
-            result += space;
-        }
-        result += string(user);
-    }
-
-    if (password != NULL) {
-        if (! result.empty()) {
-            result += space;
-        }
-        result += string(password);
-    }
-
-    return (result);
-}
-
-// Return valid connection string
 string
 validMySQLConnectionString() {
-    return (connectionString(VALID_TYPE, VALID_NAME, VALID_HOST,
+    return (connectionString(MYSQL_VALID_TYPE, VALID_NAME, VALID_HOST,
                              VALID_USER, VALID_PASSWORD));
 }
 
-// @brief Clear everything from the database
-//
-// There is no error checking in this code: if something fails, one of the
-// tests will (should) fall over.
-void destroyMySQLSchema() {
-    MySqlHolder mysql;
+void destroyMySQLSchema(bool show_err) {
+    runMySQLScript(DATABASE_SCRIPTS_DIR, "mysql/dhcpdb_drop.mysql", show_err);
+}
 
-    // Open database
-    (void) mysql_real_connect(mysql, "localhost", "keatest",
-                              "keatest", "keatest", 0, NULL, 0);
+void createMySQLSchema(bool show_err) {
+    runMySQLScript(DATABASE_SCRIPTS_DIR, "mysql/dhcpdb_create.mysql",
+                   show_err);
+}
 
-    // Get rid of everything in it.
-    for (int i = 0; destroy_statement[i] != NULL; ++i) {
-        (void) mysql_query(mysql, destroy_statement[i]);
+void runMySQLScript(const std::string& path, const std::string& script_name,
+                    bool show_err) {
+    std::ostringstream cmd;
+    cmd << "mysql -N -B --user=keatest --password=keatest keatest";
+    if (!show_err) {
+        cmd << " 2>/dev/null ";
     }
-}
 
-// @brief Create the Schema
-//
-// Creates all the tables in what is assumed to be an empty database.
-//
-// There is no error checking in this code: if it fails, one of the tests
-// will fall over.
-void createMySQLSchema() {
-    MySqlHolder mysql;
+    if (!path.empty()) {
+        cmd << " < " << path << "/";
+    }
 
-    // Open database
-    (void) mysql_real_connect(mysql, "localhost", "keatest",
-                              "keatest", "keatest", 0, NULL, 0);
+    cmd << script_name;
 
-    // Execute creation statements.
-    for (int i = 0; create_statement[i] != NULL; ++i) {
-        ASSERT_EQ(0, mysql_query(mysql, create_statement[i]))
-            << "Failed on statement " << i << ": " << create_statement[i]
-            << " error: " << mysql_error(mysql) << " (error code "
-            << mysql_errno(mysql) << ")";
-    }
+    int retval = ::system(cmd.str().c_str());
+    ASSERT_EQ(0, retval) << "runMySQLSchema failed:" << cmd.str();
 }
 
+
 };
 };
 };

+ 39 - 32
src/lib/dhcpsrv/testutils/mysql_schema.h

@@ -1,4 +1,4 @@
-// Copyright (C) 2015 Internet Systems Consortium, Inc. ("ISC")
+// Copyright (C) 2015-2016 Internet Systems Consortium, Inc. ("ISC")
 //
 // This Source Code Form is subject to the terms of the Mozilla Public
 // License, v. 2.0. If a copy of the MPL was not distributed with this
@@ -8,52 +8,59 @@
 #define TEST_MYSQL_SCHEMA_H
 
 #include <config.h>
+#include <dhcpsrv/testutils/schema.h>
 #include <string>
 
 namespace isc {
 namespace dhcp {
 namespace test {
 
-extern const char* VALID_TYPE;
-extern const char* INVALID_TYPE;
-extern const char* VALID_NAME;
-extern const char* INVALID_NAME;
-extern const char* VALID_HOST;
-extern const char* INVALID_HOST;
-extern const char* VALID_USER;
-extern const char* INVALID_USER;
-extern const char* VALID_PASSWORD;
-extern const char* INVALID_PASSWORD;
+extern const char* MYSQL_VALID_TYPE;
 
-/// @brief Create the Schema
-///
-/// Creates all the tables in what is assumed to be an empty database.
+/// Return valid connection string
 ///
-/// There is no error checking in this code: if it fails, one of the tests
-/// will fall over.
-void createMySQLSchema();
+/// @return valid MySQL connection string.
+std::string validMySQLConnectionString();
 
 /// @brief Clear everything from the database
 ///
-/// There is no error checking in this code: if something fails, one of the
-/// tests will (should) fall over.
-void destroyMySQLSchema();
+/// Submits the current schema drop script:
+///
+///  <TEST_ADMIN_SCRIPTS_DIR>/mysql/dhcpdb_drop.mysql
+///
+/// to the unit test MySQL database. If the script fails, the invoking test
+/// will fail. The output of stderr is suppressed unless the parameter,
+/// show_err is true.
+///
+/// @param show_err flag which governs whether or not stderr is suppressed.
+void destroyMySQLSchema(bool show_err = false);
 
-/// Return valid connection string
+/// @brief Create the MySQL Schema
 ///
-/// @return valid MySQL connection string.
-std::string validMySQLConnectionString();
+/// Submits the current schema creation script:
+///
+///  <TEST_ADMIN_SCRIPTS_DIR>/mysql/dhcpdb_create.mysql
+///
+/// to the unit test MySQL database. If the script fails, the invoking test
+/// will fail. The output of stderr is suppressed unless the parameter,
+/// show_err is true.
+///
+/// @param show_err flag which governs whether or not stderr is suppressed.
+void createMySQLSchema(bool show_err = false);
 
-/// @brief Given a combination of strings above, produce a connection string.
+/// @brief Run a MySQL SQL script against the MySQL unit test database
+///
+/// Submits the given SQL script to MySQL via mysql CLI. The output of
+/// stderr is suppressed unless the parameter, show_err is true.  The is done
+/// to suppress warnings that might otherwise make test output needlessly
+/// noisy.  A gtest assertion occurs if the script fails to execute.
 ///
-/// @param type type of the database
-/// @param name name of the database to connect to
-/// @param host hostname
-/// @param user username used to authendicate during connection attempt
-/// @param password password used to authendicate during connection attempt
-/// @return string containing all specified parameters
-std::string connectionString(const char* type, const char* name, const char* host,
-                             const char* user, const char* password);
+/// @param path - path (if not blank) of the script to execute
+/// @param script_name - file name of the path to execute
+/// @param show_err flag which governs whether or not stderr is suppressed.
+void runMySQLScript(const std::string& path, const std::string& script_name,
+                    bool show_err);
+
 };
 };
 };

+ 64 - 0
src/lib/dhcpsrv/testutils/pgsql_schema.cc

@@ -0,0 +1,64 @@
+// Copyright (C) 2016 Internet Systems Consortium, Inc. ("ISC")
+//
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+#include <config.h>
+#include <string>
+#include <dhcpsrv/testutils/pgsql_schema.h>
+
+#include <gtest/gtest.h>
+#include <libpq-fe.h>
+
+#include <fstream>
+#include <sstream>
+#include <stdlib.h>
+
+using namespace std;
+
+namespace isc {
+namespace dhcp {
+namespace test {
+
+const char* PGSQL_VALID_TYPE = "type=postgresql";
+
+string
+validPgSQLConnectionString() {
+    return (connectionString(PGSQL_VALID_TYPE, VALID_NAME, VALID_HOST,
+                             VALID_USER, VALID_PASSWORD));
+}
+
+void destroyPgSQLSchema(bool show_err) {
+    runPgSQLScript(DATABASE_SCRIPTS_DIR, "pgsql/dhcpdb_drop.pgsql",
+                   show_err);
+}
+
+void createPgSQLSchema(bool show_err) {
+    runPgSQLScript(DATABASE_SCRIPTS_DIR, "pgsql/dhcpdb_create.pgsql",
+                   show_err);
+}
+
+void runPgSQLScript(const std::string& path, const std::string& script_name,
+                    bool show_err) {
+    std::ostringstream cmd;
+
+    cmd << "export PGPASSWORD=keatest; cat ";
+    if (!path.empty()) {
+        cmd << " < " << path << "/";
+    }
+
+    cmd << script_name
+        << " | psql --set ON_ERROR_STOP=1 -A -t -q -U keatest -d keatest";
+
+    if (!show_err) {
+        cmd << " 2>/dev/null ";
+    }
+
+    int retval = ::system(cmd.str().c_str());
+    ASSERT_EQ(0, retval) << "runPgSQLSchema failed:" << cmd.str();
+}
+
+};
+};
+};

+ 68 - 0
src/lib/dhcpsrv/testutils/pgsql_schema.h

@@ -0,0 +1,68 @@
+// Copyright (C) 2016 Internet Systems Consortium, Inc. ("ISC")
+//
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+#ifndef TEST_PGSQL_SCHEMA_H
+#define TEST_PGSQL_SCHEMA_H
+
+#include <config.h>
+#include <dhcpsrv/testutils/schema.h>
+#include <string>
+
+namespace isc {
+namespace dhcp {
+namespace test {
+
+extern const char* PGSQL_VALID_TYPE;
+
+/// Return valid connection string
+///
+/// @return valid PgSQL connection string.
+std::string validPgSQLConnectionString();
+
+/// @brief Clear everything from the database
+///
+/// Submits the current schema drop script:
+///
+///  <TEST_ADMIN_SCRIPTS_DIR>/pgsql/dhcpdb_drop.pgsql
+///
+/// to the unit test Postgresql database. If the script fails, the invoking
+/// test will fail. The output of stderr is suppressed unless the parameter,
+/// show_err is true.
+///
+/// @param show_err flag which governs whether or not stderr is suppressed.
+void destroyPgSQLSchema(bool show_err = false);
+
+/// @brief Create the Postgresql Schema
+///
+/// Submits the current schema creation script:
+///
+///  <TEST_ADMIN_SCRIPTS_DIR>/pgsql/dhcpdb_create.pgsql
+///
+/// to the unit test Postgresql database. If the script fails, the invoking
+/// test will fail. The output of stderr is suppressed unless the parameter,
+/// show_err is true.
+///
+/// @param show_err flag which governs whether or not stderr is suppressed.
+void createPgSQLSchema(bool show_err = false);
+
+/// @brief Run a PgSQL SQL script against the Postgresql unit test database
+///
+/// Submits the given SQL script to Postgresql via psql CLI. The output of
+/// stderr is suppressed unless the parameter, show_err is true.  The is done
+/// to suppress warnings that might otherwise make test output needlessly
+/// noisy.  A gtest assertion occurs if the script fails to execute.
+///
+/// @param path - path (if not blank) of the script to execute
+/// @param script_name - file name of the path to execute
+/// @param show_err flag which governs whether or not stderr is suppressed.
+void runPgSQLScript(const std::string& path, const std::string& script_name,
+                    bool show_err);
+
+};
+};
+};
+
+#endif

+ 73 - 0
src/lib/dhcpsrv/testutils/schema.cc

@@ -0,0 +1,73 @@
+// Copyright (C) 2016 Internet Systems Consortium, Inc. ("ISC")
+//
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+#include <config.h>
+#include <string>
+
+using namespace std;
+
+namespace isc {
+namespace dhcp {
+namespace test {
+
+// Connection strings.
+// Database: keatest
+// Host: localhost
+// Username: keatest
+// Password: keatest
+
+const char* INVALID_TYPE = "type=unknown";
+const char* VALID_NAME = "name=keatest";
+const char* INVALID_NAME = "name=invalidname";
+const char* VALID_HOST = "host=localhost";
+const char* INVALID_HOST = "host=invalidhost";
+const char* VALID_USER = "user=keatest";
+const char* INVALID_USER = "user=invaliduser";
+const char* VALID_PASSWORD = "password=keatest";
+const char* INVALID_PASSWORD = "password=invalid";
+
+string connectionString(const char* type, const char* name, const char* host,
+                        const char* user, const char* password) {
+    const string space = " ";
+    string result = "";
+
+    if (type != NULL) {
+        result += string(type);
+    }
+    if (name != NULL) {
+        if (! result.empty()) {
+            result += space;
+        }
+        result += string(name);
+    }
+
+    if (host != NULL) {
+        if (! result.empty()) {
+            result += space;
+        }
+        result += string(host);
+    }
+
+    if (user != NULL) {
+        if (! result.empty()) {
+            result += space;
+        }
+        result += string(user);
+    }
+
+    if (password != NULL) {
+        if (! result.empty()) {
+            result += space;
+        }
+        result += string(password);
+    }
+
+    return (result);
+}
+
+};
+};
+};

+ 41 - 0
src/lib/dhcpsrv/testutils/schema.h

@@ -0,0 +1,41 @@
+// Copyright (C) 2016 Internet Systems Consortium, Inc. ("ISC")
+//
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+#ifndef SCHEMA_H
+#define SCHEMA_H
+
+#include <config.h>
+#include <string>
+
+namespace isc {
+namespace dhcp {
+namespace test {
+
+extern const char* INVALID_TYPE;
+extern const char* VALID_NAME;
+extern const char* INVALID_NAME;
+extern const char* VALID_HOST;
+extern const char* INVALID_HOST;
+extern const char* VALID_USER;
+extern const char* INVALID_USER;
+extern const char* VALID_PASSWORD;
+extern const char* INVALID_PASSWORD;
+/// @brief Given a combination of strings above, produce a connection string.
+///
+/// @param type type of the database
+/// @param name name of the database to connect to
+/// @param host hostname
+/// @param user username used to authendicate during connection attempt
+/// @param password password used to authendicate during connection attempt
+/// @return string containing all specified parameters
+std::string connectionString(const char* type, const char* name,
+                             const char* host, const char* user,
+                             const char* password);
+};
+};
+};
+
+#endif

+ 0 - 301
src/lib/dhcpsrv/testutils/schema_mysql_copy.h

@@ -1,301 +0,0 @@
-// Copyright (C) 2012-2015 Internet Systems Consortium, Inc. ("ISC")
-//
-// This Source Code Form is subject to the terms of the Mozilla Public
-// License, v. 2.0. If a copy of the MPL was not distributed with this
-// file, You can obtain one at http://mozilla.org/MPL/2.0/.
-
-#ifndef SCHEMA_COPY_H
-#define SCHEMA_COPY_H
-
-namespace {
-
-// What follows is a set of statements that creates a copy of the schema
-// in the test database.  It is used by the MySQL unit test prior to each
-// test.
-//
-// Each SQL statement is a single string.  The statements are not terminated
-// by semicolons, and the strings must end with a comma.  The final line
-// statement must be NULL (not in quotes)
-
-// NOTE: This file mirrors the schema in src/lib/dhcpsrv/dhcpdb_create.mysql.
-//       If this file is altered, please ensure that any change is compatible
-//       with the schema in dhcpdb_create.mysql.
-
-// Deletion of existing tables.
-
-const char* destroy_statement[] = {
-    // Turning off referential integrity checks ensures tables get dropped
-    "SET SESSION FOREIGN_KEY_CHECKS = 0",
-    "DROP TABLE lease4",
-    "DROP TABLE lease6",
-    "DROP TABLE lease6_types",
-    "DROP TABLE lease_hwaddr_source",
-    "DROP TABLE schema_version",
-    "DROP TABLE ipv6_reservations",
-    "DROP TABLE hosts",
-    "DROP TABLE dhcp4_options",
-    "DROP TABLE dhcp6_options",
-    "DROP TABLE host_identifier_type",
-
-    "DROP TRIGGER host_BDEL",
-    NULL
-};
-
-// Creation of the new tables.
-
-const char* create_statement[] = {
-
-    // Schema initialization to 1.0 starts here.
-    "START TRANSACTION",
-    "CREATE TABLE lease4 ("
-        "address INT UNSIGNED PRIMARY KEY NOT NULL,"
-        "hwaddr VARBINARY(20),"
-        "client_id VARBINARY(128),"
-        "valid_lifetime INT UNSIGNED,"
-        "expire TIMESTAMP,"
-        "subnet_id INT UNSIGNED,"
-        "fqdn_fwd BOOL,"
-        "fqdn_rev BOOL,"
-        "hostname VARCHAR(255)"
-        ") ENGINE = INNODB",
-
-    "CREATE INDEX lease4_by_hwaddr_subnet_id ON lease4 (hwaddr, subnet_id)",
-
-    "CREATE INDEX lease4_by_client_id_subnet_id ON lease4 (client_id, subnet_id)",
-
-    "CREATE TABLE lease6 ("
-        "address VARCHAR(39) PRIMARY KEY NOT NULL,"
-        "duid VARBINARY(128),"
-        "valid_lifetime INT UNSIGNED,"
-        "expire TIMESTAMP,"
-        "subnet_id INT UNSIGNED,"
-        "pref_lifetime INT UNSIGNED,"
-        "lease_type TINYINT,"
-        "iaid INT UNSIGNED,"
-        "prefix_len TINYINT UNSIGNED,"
-        "fqdn_fwd BOOL,"
-        "fqdn_rev BOOL,"
-        "hostname VARCHAR(255)"
-        ") ENGINE = INNODB",
-
-    "CREATE INDEX lease6_by_iaid_subnet_id_duid ON lease6 (iaid, subnet_id, duid)",
-
-    "CREATE TABLE lease6_types ("
-        "lease_type TINYINT PRIMARY KEY NOT NULL,"
-        "name VARCHAR(5)"
-        ") ENGINE = INNODB",
-
-    "INSERT INTO lease6_types VALUES (0, \"IA_NA\")",
-    "INSERT INTO lease6_types VALUES (1, \"IA_TA\")",
-    "INSERT INTO lease6_types VALUES (2, \"IA_PD\")",
-
-    "CREATE TABLE schema_version ("
-        "version INT PRIMARY KEY NOT NULL,"
-        "minor INT"
-        ") ENGINE = INNODB",
-
-    "INSERT INTO schema_version VALUES (1, 0)",
-    "COMMIT",
-
-    // Schema initialization to 1.0 ends here.
-
-    // Schema upgrade to 2.0 starts here.
-    "ALTER TABLE lease6 "
-        "ADD COLUMN hwaddr varbinary(20),"
-        "ADD COLUMN hwtype smallint unsigned,"
-        "ADD COLUMN hwaddr_source int unsigned;",
-
-    // Production schema has lease_hwaddr_source table. It is not used by
-    // kea code and is simply useful for formulating more human readable
-    // queries. Hence no need to create it in tests. The actual SQL
-    // code remains here commented out to keep a trace that the omission
-    // is intentional.
-
-    /* "CREATE TABLE lease_hwaddr_source ("
-    "hwaddr_source INT PRIMARY KEY NOT NULL,"
-    "name VARCHAR(40) )",
-
-    "INSERT INTO lease_hwaddr_source VALUES (1, \"HWADDR_SOURCE_RAW\");",
-    "INSERT INTO lease_hwaddr_source VALUES (2, \"HWADDR_SOURCE_IPV6_LINK_LOCAL\");",
-    "INSERT INTO lease_hwaddr_source VALUES (4, \"HWADDR_SOURCE_DUID\");",
-    "INSERT INTO lease_hwaddr_source VALUES (8, \"HWADDR_SOURCE_CLIENT_ADDR_RELAY_OPTION\");",
-    "INSERT INTO lease_hwaddr_source VALUES (16, \"HWADDR_SOURCE_REMOTE_ID\");",
-    "INSERT INTO lease_hwaddr_source VALUES (32, \"HWADDR_SOURCE_SUBSCRIBER_ID\");",
-    "INSERT INTO lease_hwaddr_source VALUES (64, \"HWADDR_SOURCE_DOCSIS\");", */
-
-    "UPDATE schema_version SET version=\"2\", minor=\"0\";",
-    // Schema upgrade to 2.0 ends here.
-
-    // Schema upgrade to 3.0 starts here.
-
-    "CREATE TABLE IF NOT EXISTS hosts ("
-        "host_id INT UNSIGNED NOT NULL AUTO_INCREMENT,"
-        "dhcp_identifier VARBINARY(128) NOT NULL,"
-        "dhcp_identifier_type TINYINT NOT NULL,"
-        "dhcp4_subnet_id INT UNSIGNED NULL,"
-        "dhcp6_subnet_id INT UNSIGNED NULL,"
-        "ipv4_address INT UNSIGNED NULL,"
-        "hostname VARCHAR(255) NULL,"
-        "dhcp4_client_classes VARCHAR(255) NULL,"
-        "dhcp6_client_classes VARCHAR(255) NULL,"
-        "PRIMARY KEY (host_id),"
-        "INDEX key_dhcp4_identifier_subnet_id (dhcp_identifier ASC , dhcp_identifier_type ASC),"
-        "INDEX key_dhcp6_identifier_subnet_id (dhcp_identifier ASC , dhcp_identifier_type ASC , dhcp6_subnet_id ASC)"
-    ")  ENGINE=INNODB",
-
-    "CREATE TABLE IF NOT EXISTS ipv6_reservations ("
-        "reservation_id INT NOT NULL AUTO_INCREMENT,"
-        "address VARCHAR(39) NOT NULL,"
-        "prefix_len TINYINT(3) UNSIGNED NOT NULL DEFAULT 128,"
-        "type TINYINT(4) UNSIGNED NOT NULL DEFAULT 0,"
-        "dhcp6_iaid INT UNSIGNED NULL,"
-        "host_id INT UNSIGNED NOT NULL,"
-        "PRIMARY KEY (reservation_id),"
-        "INDEX fk_ipv6_reservations_host_idx (host_id ASC),"
-        "CONSTRAINT fk_ipv6_reservations_Host FOREIGN KEY (host_id)"
-            "REFERENCES hosts (host_id)"
-            "ON DELETE NO ACTION ON UPDATE NO ACTION"
-    ")  ENGINE=INNODB",
-
-    "CREATE TABLE IF NOT EXISTS dhcp4_options ("
-        "option_id INT UNSIGNED NOT NULL AUTO_INCREMENT,"
-        "code TINYINT UNSIGNED NOT NULL,"
-        "value BLOB NULL,"
-        "formatted_value TEXT NULL,"
-        "space VARCHAR(128) NULL,"
-        "persistent TINYINT(1) NOT NULL DEFAULT 0,"
-        "dhcp_client_class VARCHAR(128) NULL,"
-        "dhcp4_subnet_id INT NULL,"
-        "host_id INT UNSIGNED NULL,"
-        "PRIMARY KEY (option_id),"
-        "UNIQUE INDEX option_id_UNIQUE (option_id ASC),"
-        "INDEX fk_options_host1_idx (host_id ASC),"
-        "CONSTRAINT fk_options_host1 FOREIGN KEY (host_id)"
-            "REFERENCES hosts (host_id)"
-            "ON DELETE NO ACTION ON UPDATE NO ACTION"
-    ")  ENGINE=INNODB",
-
-    "CREATE TABLE IF NOT EXISTS dhcp6_options ("
-        "option_id INT UNSIGNED NOT NULL AUTO_INCREMENT,"
-        "code INT UNSIGNED NOT NULL,"
-        "value BLOB NULL,"
-        "formatted_value TEXT NULL,"
-        "space VARCHAR(128) NULL,"
-        "persistent TINYINT(1) NOT NULL DEFAULT 0,"
-        "dhcp_client_class VARCHAR(128) NULL,"
-        "dhcp6_subnet_id INT NULL,"
-        "host_id INT UNSIGNED NULL,"
-        "PRIMARY KEY (option_id),"
-        "UNIQUE INDEX option_id_UNIQUE (option_id ASC),"
-        "INDEX fk_options_host1_idx (host_id ASC),"
-        "CONSTRAINT fk_options_host10 FOREIGN KEY (host_id)"
-            "REFERENCES hosts (host_id)"
-            "ON DELETE NO ACTION ON UPDATE NO ACTION"
-    ")  ENGINE=INNODB",
-
-
-    //"DELIMITER $$ ",
-    "CREATE TRIGGER host_BDEL BEFORE DELETE ON hosts FOR EACH ROW "
-    "BEGIN "
-    "DELETE FROM ipv6_reservations WHERE ipv6_reservations.host_id = OLD.host_id; "
-    "END ",
-    //"$$ ",
-    //"DELIMITER ;",
-
-    "UPDATE schema_version SET version = '3', minor = '0';",
-
-    // This line concludes database upgrade to version 3.0.
-
-    // Schema upgrade to 4.0 starts here.
-    "ALTER TABLE lease4 "
-        "ADD COLUMN state INT UNSIGNED DEFAULT 0",
-
-    "ALTER TABLE lease6 "
-        "ADD COLUMN state INT UNSIGNED DEFAULT 0",
-
-    "CREATE INDEX lease4_by_state_expire ON lease4 (state ASC, expire ASC)",
-    "CREATE INDEX lease6_by_state_expire ON lease6 (state ASC, expire ASC)",
-
-    // Production schema includes the lease_state table and
-    // lease_hwaddr_source tables which map to the values in lease4
-    // and lease6 tables. This is not used in the unit tests
-    // so it is commented out.
-
-    /*"CREATE TABLE IF NOT EXISTS lease_state (",
-        "state INT UNSIGNED PRIMARY KEY NOT NULL,"
-        "name VARCHAR(64) NOT NULL);",
-
-    "INSERT INTO lease_state VALUES (0, \"default\");",
-    "INSERT INTO lease_state VALUES (1, \"declined\");",
-    "INSERT INTO lease_state VALUES (2, \"expired-reclaimed\");",
-
-    "ALTER TABLE lease4 "
-        "ADD CONSTRAINT fk_lease4_state FOREIGN KEY (state) "
-        "REFERENCES lease_state (state)",
-
-    "ALTER TABLE lease6 "
-        "ADD CONSTRAINT fk_lease6_state FOREIGN KEY (state) "
-        "REFERENCES lease_state (state)",
-
-    "ALTER TABLE lease6 "
-        "ADD CONSTRAINT fk_lease6_type FOREIGN KEY (lease_type) "
-        "REFERENCES lease6_types (lease_type)",
-
-    "UPDATE lease_hwaddr_source "
-        "SET name = 'HWADDR_SOURCE_DOCSIS_CMTS' "
-        "WHERE hwaddr_source = 64",
-
-    "INSERT INTO lease_hwaddr_source VALUES (128, 'HWADDR_SOURCE_DOCSIS_MODEM')",
-
-    "ALTER TABLE lease_hwaddr_source "
-        "MODIFY COLUMN hwaddr_source INT UNSIGNED NOT NULL DEFAULT 0",
-
-    "ALTER TABLE lease6 "
-        "ADD CONSTRAINT fk_lease6_hwaddr_source FOREIGN KEY (hwaddr_source) "
-        "REFERENCES lease_hwaddr_source (hwaddr_source)",*/
-
-    // Schema upgrade to 4.0 ends here.
-
-    "DROP INDEX key_dhcp4_identifier_subnet_id ON hosts",
-    "CREATE UNIQUE INDEX key_dhcp4_identifier_subnet_id "
-      "ON hosts "
-        "(dhcp_identifier ASC , dhcp_identifier_type ASC , dhcp4_subnet_id ASC)",
-
-    "DROP INDEX key_dhcp6_identifier_subnet_id ON hosts",
-    "CREATE UNIQUE INDEX key_dhcp6_identifier_subnet_id "
-      "ON hosts "
-        "(dhcp_identifier ASC , dhcp_identifier_type ASC , dhcp6_subnet_id ASC)",
-
-    "CREATE UNIQUE INDEX key_dhcp4_ipv4_address_subnet_id "
-      "ON hosts "
-        "(ipv4_address ASC, dhcp4_subnet_id ASC)",
-
-    "CREATE UNIQUE INDEX key_dhcp6_address_prefix_len "
-      "ON ipv6_reservations (address ASC , prefix_len ASC)",
-
-    "CREATE TABLE IF NOT EXISTS host_identifier_type ("
-      "type TINYINT PRIMARY KEY NOT NULL,"
-      "name VARCHAR(32)"
-    ") ENGINE = INNODB",
-
-    "START TRANSACTION",
-    "INSERT INTO host_identifier_type VALUES (0, \"hw-address\")",
-    "INSERT INTO host_identifier_type VALUES (1, \"duid\")",
-    "INSERT INTO host_identifier_type VALUES (2, \"circuit-id\")",
-    "COMMIT",
-
-    "ALTER TABLE hosts "
-    "ADD CONSTRAINT fk_host_identifier_type FOREIGN KEY (dhcp_identifier_type) "
-      "REFERENCES host_identifier_type (type)",
-
-    "UPDATE schema_version "
-      "SET version = '4', minor = '2'",
-
-    // Schema upgrade to 4.2 ends here.
-
-    NULL
-};
-
-};  // Anonymous namespace
-
-#endif // SCHEMA_COPY_H

+ 1 - 0
src/share/Makefile.am

@@ -0,0 +1 @@
+SUBDIRS = database

+ 1 - 0
src/share/database/Makefile.am

@@ -0,0 +1 @@
+SUBDIRS = scripts

src/bin/admin/scripts/Makefile.am → src/share/database/scripts/Makefile.am


src/bin/admin/scripts/mysql/.gitignore → src/share/database/scripts/mysql/.gitignore


+ 1 - 0
src/bin/admin/scripts/mysql/Makefile.am

@@ -2,6 +2,7 @@ SUBDIRS = .
 
 sqlscriptsdir = ${datarootdir}/${PACKAGE_NAME}/scripts/mysql
 sqlscripts_DATA = dhcpdb_create.mysql
+sqlscripts_DATA += dhcpdb_drop.mysql
 sqlscripts_DATA += upgrade_1.0_to_2.0.sh
 sqlscripts_DATA += upgrade_2.0_to_3.0.sh
 sqlscripts_DATA += upgrade_3.0_to_4.0.sh

src/bin/admin/scripts/mysql/dhcpdb_create.mysql → src/share/database/scripts/mysql/dhcpdb_create.mysql


+ 24 - 0
src/share/database/scripts/mysql/dhcpdb_drop.mysql

@@ -0,0 +1,24 @@
+# Copyright (C) 2016 Internet Systems Consortium.
+#
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+# Turn off foreign key checks as CASCADE isn't really supported in MySQL
+SET SESSION FOREIGN_KEY_CHECKS = 0;
+DROP TABLE IF EXISTS lease4;
+DROP TABLE IF EXISTS lease6;
+DROP TABLE IF EXISTS lease6_types;
+DROP TABLE IF EXISTS lease_hwaddr_source;
+DROP TABLE IF EXISTS schema_version;
+DROP TABLE IF EXISTS ipv6_reservations;
+DROP TABLE IF EXISTS hosts;
+DROP TABLE IF EXISTS dhcp4_options;
+DROP TABLE IF EXISTS dhcp6_options;
+DROP TABLE IF EXISTS host_identifier_type;
+DROP TABLE IF EXISTS lease_state;
+DROP TRIGGER IF EXISTS host_BDEL;
+DROP PROCEDURE IF EXISTS lease4DumpHeader;
+DROP PROCEDURE IF EXISTS lease4DumpData;
+DROP PROCEDURE IF EXISTS lease6DumpHeader;
+DROP PROCEDURE IF EXISTS lease6DumpData;

src/bin/admin/scripts/mysql/upgrade_1.0_to_2.0.sh.in → src/share/database/scripts/mysql/upgrade_1.0_to_2.0.sh.in


src/bin/admin/scripts/mysql/upgrade_2.0_to_3.0.sh.in → src/share/database/scripts/mysql/upgrade_2.0_to_3.0.sh.in


src/bin/admin/scripts/mysql/upgrade_3.0_to_4.0.sh.in → src/share/database/scripts/mysql/upgrade_3.0_to_4.0.sh.in


src/bin/admin/scripts/mysql/upgrade_4.0_to_4.1.sh.in → src/share/database/scripts/mysql/upgrade_4.0_to_4.1.sh.in


src/bin/admin/scripts/pgsql/.gitignore → src/share/database/scripts/pgsql/.gitignore


+ 1 - 0
src/bin/admin/scripts/pgsql/Makefile.am

@@ -2,6 +2,7 @@ SUBDIRS = .
 
 sqlscriptsdir = ${datarootdir}/${PACKAGE_NAME}/scripts/pgsql
 sqlscripts_DATA = dhcpdb_create.pgsql
+sqlscripts_DATA += dhcpdb_drop.pgsql
 sqlscripts_DATA += upgrade_1.0_to_2.0.sh
 
 EXTRA_DIST = ${sqlscripts_DATA}

+ 1 - 0
src/bin/admin/scripts/pgsql/dhcpdb_create.pgsql

@@ -1,4 +1,4 @@
+-- Copyright (C) 2012-2016 Internet Systems Consortium.
 
 -- This Source Code Form is subject to the terms of the Mozilla Public
 -- License, v. 2.0. If a copy of the MPL was not distributed with this

+ 15 - 0
src/share/database/scripts/pgsql/dhcpdb_drop.pgsql

@@ -0,0 +1,15 @@
+-- Copyright (C) 2016 Internet Systems Consortium.
+
+-- This Source Code Form is subject to the terms of the Mozilla Public
+-- License, v. 2.0. If a copy of the MPL was not distributed with this
+-- file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+DROP TABLE IF EXISTS lease4 CASCADE;
+DROP TABLE IF EXISTS lease6 CASCADE;
+DROP TABLE IF EXISTS lease6_types CASCADE;
+DROP TABLE IF EXISTS schema_version CASCADE;
+DROP TABLE IF EXISTS lease_state CASCADE;
+DROP FUNCTION IF EXISTS lease4DumpHeader();
+DROP FUNCTION IF EXISTS lease4DumpData();
+DROP FUNCTION IF EXISTS lease6DumpHeader();
+DROP FUNCTION IF EXISTS lease6DumpData();

src/bin/admin/scripts/pgsql/upgrade_1.0_to_2.0.sh.in → src/share/database/scripts/pgsql/upgrade_1.0_to_2.0.sh.in